需要为每个连接创建一个新线程。线程应具有写入套接字的功能,即使它在run()中等待客户端输入:String clientCommand = in.readLine()
。函数update
应满足此要求,并且能够使用PrintWriter outWr
写入套接字,但它似乎是null
,即使在线程构造函数中设置它也是如此。
无法在构造函数中初始化PrintWriter outWr
。 try
构建后outWr
仍然是null
。如何解决?
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);}
答案 0 :(得分: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(