網絡編程bio流程Java demo

服務端:監聽端口,負責處理鏈接請求,業務處理,返回結果給客戶端socket

public class Server {
    private static String s = "Hello World!";

    static byte[] result = new byte[1024];

    public static void main(String[] args) throws Exception {
        //1.服務端綁定端口,創建監聽
        ServerSocket serverSocket = new ServerSocket(8080);

        //2.不斷輪詢,獲取新的請求
        while(true){

            //3.accept接受鏈接,並阻塞獲取鏈接
            Socket socket = serverSocket.accept();

            //4.讀取客戶端鏈接中,傳輸過來的數據
            socket.getInputStream().read(result);
            System.out.println("接受到客戶端數據:" + new String(result));

            //5.業務邏輯處理,寫回數據到socket鏈接中
            socket.getOutputStream().write(s.getBytes());
        }
    }
}

客戶端:經過IP和端口信息,與服務端創建鏈接,發送數據給服務端,接受服務端業務處理結果server

public class Client {
    static String s = "我是客戶端1";
    static byte[] result = new byte[1024];

    public static void main(String[] args) throws Exception{
        //1.客戶端創建綁定,並創建鏈接
        Socket socket = new Socket("192.168.0.156", 8080);

        //2.客戶端發送數據給服務端
        socket.getOutputStream().write( s.getBytes());
        System.out.println("發送數據到服務端:" + s);

        //3.客戶端從socket讀取,服務端業務處理結果
        SocketAddress socketAddress = socket.getLocalSocketAddress();
        InputStream in =  socket.getInputStream();
        in.read(result);
        System.out.println("接收服務數據:" + new String(result));
    }
}
相關文章
相關標籤/搜索