2012-06-02 105 views
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);} 

回答

4

看看這段代碼

public class ClientServiceThread extends Thread { 
private PrintWriter outWr; 

ClientServiceThread(Socket s, int clientID, Auction a) { 
     try { 
      PrintWriter outWr = new PrintWriter(new OutputStreamWriter(

在構造函數中你沒有一流的領域,但本地參考PrintWriter outWr

更改它初始化爲

 try { 
      outWr = new PrintWriter(new OutputStreamWriter(