TCP

TCP

  • 客户端

    1. 连接服务器Socket
    2. 发送消息
    //客户端
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        //了解服务器的地址
        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            //端口号
            int port = 9999;
            //创建一个socket连接
            socket = new Socket(inetAddress, port);
            //发送消息:IO流
            outputStream = socket.getOutputStream();
            outputStream.write("测试成功!".getBytes());
    
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
    
  • 服务器

    1. 建立服务的端口ServerSocket
    2. 等待用户的连接accept
    3. 接收消息
    //服务端
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream inputStream=null;
        ByteArrayOutputStream baos=null;
    
        //需要有一个地址
        try {
            serverSocket = new ServerSocket(9999);
            //等待客户端连接
            socket = serverSocket.accept();
            //读取客户端消息
            inputStream = socket.getInputStream();
            //管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int len;
            while((len=inputStream.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
posted @ 2021-04-16 17:19  saxon宋  阅读(52)  评论(0)    收藏  举报