用java代码制作一个tcp的服务端,要求被多个客户端同时连接,当客户端连上时,主动发送任意字符串,等待客户端返回任意信息,当客户端有返回时,立即关闭socket,如果在设置的超时时间内没有返回,也关闭socket。
时间: 2023-06-04 21:02:51 浏览: 158
好的,以下是Java代码实现一个TCP服务端,可以被多个客户端同时连接,等待客户端发送任意信息,如果在设置的超时时间内没有返回,则关闭socket:
```java
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TCPServer {
private ServerSocket serverSocket;
private ExecutorService threadPool;
public TCPServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
threadPool = Executors.newCachedThreadPool();
System.out.println("TCP Server started on port " + port);
}
public void start() {
while (true) {
try {
Socket clientSocket = serverSocket.accept();
threadPool.execute(new ClientHandler(clientSocket));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
TCPServer server = new TCPServer(9000);
server.start();
}
}
class ClientHandler implements Runnable {
private Socket clientSocket;
ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try {
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write("Hello, please send a message.".getBytes());
byte[] buffer = new byte[1024];
int len = clientSocket.getInputStream().read(buffer);
if (len > 0) {
System.out.println("Received message from client: " + new String(buffer, 0, len));
} else {
System.out.println("No message received from client within the timeout.");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
该服务端使用了线程池来对多个客户端进行处理,每当有一个客户端连接,就会把它交给新的线程来处理,在向客户端发送第一次消息后,会等待客户端在一定时间内返回任意信息,如果在设置的超时时间内没有返回任何信息,则关闭socket连接。
阅读全文