我正在互联网上实现一个基于 tut 的 tcp java 客户端/服务器应用程序我更改了一些方法并收到 nullpointerexception 错误
错误来自 run()。它在扩展 Thread 类的 Connection 类中。run() 应该监听传入的通信。我启动服务器类,监听一个端口。所以我有一个成功的连接。然后当我尝试通过 run() 方法监听传入的通信时应用程序报告错误
建立连接并启动:
Connection c = new Connection(host,port);
Scanner chatConsole = new Scanner(System.in);
String text = "";
while (!text.equalsIgnoreCase("halt")){
text = chatConsole.nextLine();
c.start();
线程“Thread-1”中的异常 java.lang.NullPointerException
运行()
public void run(){//watch for incoming communication
String msg;
try{//loop reading lines and display msg
while ((msg = in.readLine()) != null) {
System.out.println(msg);
}
}catch (IOException e) {
System.err.println(e);
}
}
如果它有助于调试,这是该类的构造函数。
public Connection(String iniName, int iniPort){
host = iniName;
port = iniPort;
try {
server = new Socket(host, port);
}catch (UnknownHostException e){
System.err.println(e);
System.exit(1);
}
try{
stdIn = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(server.getOutputStream(), true); //output stream to server
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
}catch(Exception e){
System.err.println(e);
}
}
谢谢