JAVASE網路程式設計之TCP實現聊天通訊

小小雨傘發表於2020-10-02

TCPClientDemo01 類,客戶端

public class TCPClientDemo01 {

    public static void main(String[] args) {
        try {
            InetAddress name = InetAddress.getByName("127.0.0.1");
            System.out.println(name);
            int port =9999;
            //2.建立一個socket連線
            Socket socket = new Socket(name,port);
            //3.傳送訊息IO流
            OutputStream os = socket.getOutputStream();
            os.write("你好,歡迎光臨!!!".getBytes());
            os.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

TCPServerDome01 服務端接收

public class TCPServerDome01 {

    public static void main(String[] args) {
        //首先要有一個地址
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            // 2等待客戶端連線過來
            Socket accept = serverSocket.accept();
            //讀取客戶資訊
            InputStream is = accept.getInputStream();
            //使用管道流
            ByteArrayOutputStream boas = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len=is.read(buffer))!=-1){
                boas.write(buffer,0,len);
            }
            System.out.println(boas.toString());

            boas.close();
            is.close();
            accept.close();
            serverSocket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

相關文章