ServerSocket與多個客戶端一起使用我們爲每個客戶端附加單獨的線程來工作可能,但問題是連接工作正常,並接受所有客戶端,但只服務於最後一次連接。所以不是問題或者這是正常的。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());
}
}
}
ClientThread
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());
}
}
}
是的你是對的。我忘記了我在同一個ID內工作,非常感謝。如果你沒有回答我不會得到它。因爲我不會感謝它 – Alyafey 2013-04-21 23:33:22