TCP通信

TCP通信原理图解

 

案例:TCP数据传输【多练】

》客户端用键盘+死循环实现

public class Demo_Client {

    public static void main(String[] args) throws IOException {
        
        //1.创建Socket对象
        Socket socket = new Socket("192.168.1.125", 9999);
        
        //2.获取输入流出
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        PrintWriter pw = new PrintWriter(os);
        
        //3.发送数据给服务端面
        pw.write("Java 还是不错的...\r\n");
        pw.flush();
        
        //4.读服务响应的数据
        System.out.println("读取响应数据:" + br.readLine());
        
        //关流
        br.close();
        socket.close();
    }
}
public class Demo_Server {

    public static void main(String[] args) throws Exception {

        //1.创建个服务端Socket对象,绑定端口
        ServerSocket serverSocket = new ServerSocket(9999);
        
        //2.监听客户端面连接
        while(true){
            Socket clientSocket = serverSocket.accept();
            
            //3.接收客户端面发送的数据
            new Thread(){
                public void run() {
                    try {
                        //读写数据都是通过IO
                        InputStream is = clientSocket.getInputStream();
                        OutputStream os = clientSocket.getOutputStream();
                        
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        PrintWriter pw = new PrintWriter(os);
                    
                        while(true){
                            //读取客户端的数据
                            String line = br.readLine();
                            if(line != null){
                                System.out.println(clientSocket + ":" + new Date() +  "接收到客户端发送的数据:" + line);
                                
                                //响应客户端面
                                pw.write("receiver success\r\n");
                                pw.flush();
                            }    
                            
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    
                };
            }.start();
        }
    }
}

 

posted @ 2018-12-22 23:09  expworld  阅读(131)  评论(0编辑  收藏  举报