0
需要爲每個連接創建一個新線程。線程應該有函數寫入套接字,即使它在run()等待客戶端輸入:String clientCommand = in.readLine()
。函數update
應該符合此要求,並且能夠使用PrintWriter outWr
寫入套接字,但它似乎是null
,即使將它設置爲線程構造函數。 無法在構造函數中初始化PrintWriter outWr
。在try
之後建造outWr
仍然是null
。如何解決它?無法初始化線程構造函數中的PrintWriter字段
public class Server {
public static void main(String[] args) {
...
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++, auction);
...
}
public class ClientServiceThread extends Thread {
private PrintWriter outWr;
ClientServiceThread(Socket s, int clientID, Auction a) {
try {
PrintWriter outWr = new PrintWriter(new OutputStreamWriter(
m_clientSocket.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {....; String clientCommand = in.readLine(); ... }
public void update(String msg){outWr.println(msg);}