TCP通信

public class TCPclient {

    public static void main(String[] args) throws IOException   {
        // 1.创建socket对象,连接服务器
        Socket s =new Socket("127.0.0.1",8888);
        //2.通过客户端套接字对象,socket方法获取字节输出流,将数据写向服务器
        OutputStream out =s.getOutputStream();
        //3.写数据
        out.write("我是客户端,你好".getBytes());
        
        //接收服务器的回复
        InputStream in =s.getInputStream();
        byte [] b =new byte [1024];
        int len =in.read(b);
        String  ip =s.getInetAddress().getHostAddress();
        System.out.println("客户端IP:"+ip+"-"+new String(b,0,len));
        //释放资源
        s.close();
    }

}
public class TCPservice {
    public static void main(String[] args) throws IOException {
        //1.创建服务器servicesocket绑定端口号
        ServerSocket ser =new ServerSocket(8888);
        //2.调用服务器套接字对象accept方法,建立连接,获取套接字对象
        Socket s =ser.accept();
        //3.用socket 获取输入源
        InputStream in =s.getInputStream();
        //4.读数据
        byte [] b =new byte[1024];
        int len =in.read(b);
        String ip =s.getInetAddress().getHostAddress();
        System.out.println("服务器IP:"+ip+"接收的数据为:"+new String (b,0,len));
            //给客户端回复
        OutputStream out=s.getOutputStream();
        out.write("服务器收到了".getBytes());
        //释放资源
        s.close();
        ser.close();
    }
}

这是TCP协议,

一个是ServerSocket类,用于表示服务器端,一个是Socket类,用于表示客户端

ServerSocket创建对象,绑定接口

accept方法 获得套接字对象

猜你喜欢

转载自www.cnblogs.com/Jxliu/p/9234928.html