ServerSocket 要与多个客户端一起使用,我们可能为每个客户端附加单独的线程以使其工作,但问题是连接工作正常并接受所有客户端但只提供最后一个连接。所以不是问题,或者这是正常的。
服务器代码:
ServerSocket serverSocket=null;
Socket client;
System.out.println("Establishing Connection. Please wait...");
try{
serverSocket =new ServerSocket(58342);
System.out.println("Serever Started.");
}catch(Exception e)
{
System.out.println(e.getMessage());
}
while (true) {
try{
client = serverSocket.accept();
new ClientThread(client).start();
}catch(Exception e)
{
String err=e.getMessage();
if(err == null)
{
break;
}else{
System.out.println(e.getMessage());
}
}
}
客户端线程
public class ClientThread extends Thread{
private static Socket client;
private static String line="";
private static DataInputStream input = null;
private static DataOutputStream output = null;
public ClientThread(Socket serv)
{
try {
client =serv;
input=new DataInputStream(client.getInputStream());
output=new DataOutputStream(client.getOutputStream());
System.out.println("New Client Connected to port:"+
client.getPort());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}