编写简单的客户端和服务端,理解两者之间连接的建立和数据的传输(TCP)

import java.net.*;
import java.io.*;

public class TCPServer{
    
    public static void main(String[] args){
        
        try{
            ServerSocket ss = new ServerSocket(6666);
            while(true){
                Socket s = ss.accept();
                DataInputStream dis = new DataInputStream(s.getInputStream());
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                System.out.println(dis.readUTF());
                dos.writeUTF("hello,IP:" + s.getInetAddress().toString().substring(1) + " port#" + s.getPort());
                dos.flush();
                dos.close();
                dis.close();
                s.close();
            }
        } catch(IOException e){
            e.printStackTrace();
        }
    }
    
}
import java.net.Socket;
import java.io.*;

public class TCPClient{
    
    public static void main(String[] args){
        
        try{
            Socket s = new Socket("127.0.0.1", 6666);
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            DataInputStream dis = new DataInputStream(s.getInputStream());
            dos.writeUTF("我是客户端,请求连接!");
            System.out.println(dis.readUTF());
            dos.flush();
            dos.close();
            dis.close();
            s.close();
        } catch(IOException e){
            e.printStackTrace();
        }
    }
    
}

 

posted @ 2020-03-06 15:42  yxfyg  阅读(226)  评论(0)    收藏  举报