一、需求文档
使用TCP协议支持与多个客户端同时通信。
1.1 Client
package com.itheima.tcp2;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
//1、创建socket对象,并同时请求与服务端程序的连接
Socket socket = new Socket("127.0.0.1",8888);
//2、从socket通信管道中得到一个字节输出流,用来发数据给服务端程序
OutputStream os = socket.getOutputStream();
//3、把低级的字节输出流包装成数据输出流
DataOutputStream dos = new DataOutputStream(os);
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请说:");
String msg = sc.nextLine();
//退出
if ("exit".equals(msg)) {
System.out.println("欢迎下次光临!退出成功");
dos.close();
socket.close();
break;
}
//4、开始写数据出去
dos.writeUTF(msg);
dos.flush();
}
}
}
1.2 Server
package com.itheima.tcp2;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
//启动服务端
System.out.println("-----服务端启动成功------");
//1、创建serversocket对象,同时为服务端程序注册端口
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
//2、使用serverSocket对象,调用accept方法,等待客户端的连接请求
Socket socket = serverSocket.accept();
System.out.println("有人上线了" + socket.getRemoteSocketAddress());
//3、把这个客户端对于的socket通信管道,交给一个独立的线程负责处理
new ServerReaderThread(socket).start();
}
}
}
1.3 ServerReaderThread
package com.itheima.tcp2;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class ServerReaderThread extends Thread{
private Socket socket;
public ServerReaderThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
while (true) {
try {
String msg = dis.readUTF();
System.out.println(msg);
} catch (Exception e) {
System.out.println("有人下线了!" + socket.getRemoteSocketAddress());
dis.close();
socket.close();
break;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
二、运行结果
客户端1
客户端2
客户端3
服务端