我有一個問題,我目前正在研究我的一個小項目,並偶然發現了一個死衚衕。我有一個Java服務器:Java多線程服務器客戶端
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
ServerSocket welcomeSocket = new ServerSocket(3443);
Socket clientSocket =null;
ClientHandler ch;
while(true)
{
try{
clientSocket = welcomeSocket.accept();
System.out.println("Client connected on port :"+clientSocket.getPort());
ch = new ClientHandler (clientSocket);
Thread t = new Thread(ch);
t.start();
}catch (Exception e){
System.out.println("SERVER CRASH");
}
}
}
}
然後,客戶機通過端口連接3443,一個新的線程與ClientHandler的創建。現在是問題所在,在客戶端,用於連接的套接字仍然在端口3443上,但在服務器端,線程在任意端口上,比如說5433,所以服務器可以與線程通信但不與客戶端通信,因爲它不知道線程正在使用什麼端口......我對這一切有點困惑,客戶端類只需要進行初始連接,然後所有的通信都通過ClientHandler類完成,如果所以我應該在客戶端類中實例化一個ClientHandler對象嗎?
這裏是我的客戶端類:
import java.io.*;
import java.net.*;
class TCPClient
{
static Socket clientSocket = null;
public static void main(String argv[]) throws Exception
{
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
BufferedReader ine = null;
DataOutputStream oute = null;
try{
clientSocket = new Socket("localhost", 3443);
oute = new DataOutputStream(clientSocket.getOutputStream());
ine = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host");
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
try{
//send
oute.writeBytes(k.readLine());
//recieve
String line = ine.readLine();
System.out.println("Text received: " + line);
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
}
}
}
問題是在客戶端創建仍連接到端口3443的插座上,將服務器監聽此端口,所以我不會從服務器收到任何東西(無限循環)。 clientHandler位於另一個端口上。我做錯了嗎?
所以通信只能在clientHandler中進行嗎? – Wilsane 2012-02-10 12:16:25
是的;調用'ServerSocket.accept()'的線程應儘可能快地放棄傳入連接,因爲直到再次調用accept()時,其他客戶端才能連接。 – Bombe 2012-02-10 12:18:54