TCP小记

TCP

客户端

1. 连接服务器 Socket
2. 发送消息
package basic;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TCPClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            InetAddress ia = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            socket = new Socket(ia,port);
            os = socket.getOutputStream();
            os.write("Hello,you!".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

服务器

1. 建立服务的端口 ServerSocket
2. 等待用户的链接 accept
3. 接收用户的消息
package basic;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServerDemo01 {
    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            ss = new ServerSocket(9999);
            while(true) {
                socket = ss.accept();

                is = socket.getInputStream();

                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                System.out.println(baos.toString());
            }



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

    }
}

posted @ 2021-03-24 00:04  天然卷123  阅读(0)  评论(0)    收藏  举报