public class ServerTcp {
public static void main(String[] args) throws IOException {
int port = 6666; // 选择一个端口号
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started. Listening on port " + port);
try {
while (true) {
// 无限循环,等待客户端连接
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket.getInetAddress());
// 创建一个新线程来处理请求
Thread clientHandler = new Thread(new ClientHandler(clientSocket));
clientHandler.start();
}
} finally {
serverSocket.close(); // 关闭ServerSocket
}
}
}
public class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try {
InputStream inputStream = clientSocket.getInputStream();
byte[] buff = new byte[1024];
int len;
len = inputStream.read(buff);
System.out.println(new String(buff, 0, len));
OutputStream os = clientSocket.getOutputStream();
os.write((UUID.randomUUID().toString()+"服务端返回信息").getBytes());
os.close();
inputStream.close();
} catch (
IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ClientTcp {
public static void main(String[] args) throws IOException {
Socket client = new Socket("localhost",6666);
OutputStream outputStream = client.getOutputStream();
outputStream.write("客户端请求信息".getBytes());
InputStream is = client.getInputStream();
byte[] buff = new byte[1024];
int len;
// while ((len = is.read(buff)) != -1){
// System.out.println(new String(buff,0,len));
// }
len = is.read(buff);
System.out.println(new String(buff,0,len));
is.close();
outputStream.close();
client.close();
}
}