我正在创建一个执行以下任务的服务器应用程序
- 接受来自客户端的连接
- 将每个客户端连接处理到单独的线程
- 从客户端接收数据
- 向客户端发送数据
我能够连接客户端但无法从客户端接收数据
仅当客户端断开连接时,我的控制台中才能看到数据..!!!
代码 :-
public class ServerListener {
public static void main(String[] args) {
new ServerListener().startServer();
}
public void startServer() {
final ExecutorService clientProcessingPool = Executors
.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Waiting for clients to connect...");
while (true) {
Socket clientSocket = serverSocket.accept();
clientProcessingPool
.submit(new ClientTask(clientSocket));
}
} catch (IOException e) {
System.err.println("Unable to process client request");
e.printStackTrace();
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
private class ClientTask implements Runnable {
private final Socket clientSocket;
private ClientTask(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
System.out.println("Got a client !");
try {
/* Get Data From Client */
BufferedReader reader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String clientData = "";
clientData = reader.readLine();
System.out.println("Data From Client :" + clientData);
/* Send Data To Client */
//Code
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}