首页 > 其他分享 >网络多线程

网络多线程

时间:2023-02-02 13:26:42浏览次数:51  
标签:socket 网络 new close 多线程 public 服务端 客户端

一、TCP字节流

要求:客户端发送一条消息,服务端接收并打印出来
思路:服务端要先监听某个端口,等待客户端的连接(处于阻塞状态);客户端需要知道自己是跟谁通信,要知道对方的IP及端口号,
客户端发送肯定就是把消息输出,用OutputStram
服务端是接收发送来的信息,用 InputStram

注意:要先启动服务端,自己家的大门都没打开,客人怎么可能进得去

client

public class SocketTCPClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("你好啊".getBytes());
        socket.close();
        outputStream.close();
    }
}

Server

public class SocketTCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端在9999端口等待连接");
        Socket socket = serverSocket.accept();
        System.out.println("连接成功");
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while((len=inputStream.read(buf)) != -1) {
            System.out.println(new String(buf,0,len));
        }
        socket.close();
        inputStream.close();
    }
}

标签:socket,网络,new,close,多线程,public,服务端,客户端
From: https://www.cnblogs.com/jxnote/p/17085673.html

相关文章