所以我有以下代码启动服务器并允许客户端连接到它,我有两个问题,首先,一旦客户端断开连接,我如何让服务器终止该线程?其次,这段代码允许多个连接,但是当我连接第二个用户时,服务器只响应那个套接字,不再是第一个客户端套接字。
有什么建议吗?
public Server()
{
try
{
ServerSocket server=new ServerSocket(5000); // Creating a server socket and bind it at port 5000
System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":5000");
System.out.println("The Cash Dispenser application can now connect");
while(true)
{
socket=server.accept(); // Ready to accept client request
System.out.println("Client connected with IP " + socket.getInetAddress());
new ClientThread(socket).start(); // Spawn a new thread for this socket
}
}
catch(Exception err)
{
System.err.println("* err"+err);
}
}
public class ClientThread extends Thread
{
protected Socket socket;
public ClientThread(Socket clientSocket)
{
this.socket = clientSocket;
}
public void run()
{
try
{
out=new PrintStream(socket.getOutputStream());
BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream())); // Opening the input stream to read data from client connection
}
catch (IOException e)
{
return;
}
while(true)
{
try
{
socket.getInputStream().read(inputArray);
}
catch (IOException e)
{
return;
}
if(inputArray != null)
{
for(incomingData = 0; incomingData < (inputArray.length - 1); incomingData++)
{
if(inputArray[incomingData] == ETX)
{
processData(inputArray);
break;
}
}
}
try
{
Thread.sleep(10);
}
catch (InterruptedException e1)
{
}
}
}
}