我正在開發一個簡單的Java消息傳遞程序。在開始處理更復雜的功能之前,我希望基本系統能夠正常工作。目前Java - 客戶端連接出錯
- 多個客戶端可以連接
- 多個客戶端可以使服務器接收
- 服務器關閉連接客戶端時終止
該代碼尤其顯得是什麼讓發送消息錯誤。它是我的ClientThread.java線程中的run()方法(實現可運行)。此線程用於處理來自服務器的傳入消息(發送消息正常工作)。
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class ClientThread implements Runnable{
private Socket server;
private DataInputStream in;
private DataOutputStream out;
public Text msgContent;
public void login(Stage stage, Scene main, String username, String password, String portString, String host) {
try {
int port = Integer.parseInt(portString);
this.server = new Socket(host, port);
this.in = new DataInputStream(server.getInputStream());
this.out = new DataOutputStream(server.getOutputStream());
stage.setScene(main);
Platform.runLater(new ClientThread());
}
catch (NumberFormatException e) {
System.out.println("Invalid Port");
return;
}
catch (IOException e) {
System.out.println("Error Connecting to Server");
return;
}
}
public void run() {
String msg = "";
try {
while (true) {
msg = in.readUTF(); //This line gives Errors
System.out.println("Read message from server");
msgContent.setText(msgContent.getText() + msg + "\n");
System.out.println("Added message from server to view");
}
}
catch(Exception ioe) {
ioe.printStackTrace();
System.out.println("Failed to read message from server and add to view.");
}
}
public void sendMsg(String msg) {
try {
out.writeUTF(msg);
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}
請注意,msgContent是我的JavaFX前端和服務器的inputStream中的Text對象。我的完整代碼是here。我得到的錯誤是
顯示java.lang.NullPointerException 在ClientThread.run(ClientThread.java:42) 在com.sun.javafx.application.PlatformImpl $ 6 $ 1.run(來源不明) 在com.sun.javafx.application.PlatformImpl $ 6 $ 1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl $ 6.run(Unknown Source) at com.sun.glass.ui.InvokeLaterDispatcher $ Future.run(未知源) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication。訪問300美元(未知來源) at com.sun.glass.ui.win.WinApplication $ 4 $ 1.run(Unknown Source) at java.lang.Thread.run(未知來源) 未能從服務器讀取消息並添加到視圖中。
另請注意,我使用Platform.runLater()來運行此方法。我想知道如何解決上述錯誤,以便我的代碼工作。提前致謝。空指針異常的
'in'null?我們從來沒有看到它的定義或聲明。 – Wug 2014-11-05 22:48:36
編號'in'不爲空。試試[GitHub Page](http://www.github.com/xv435/JavaMSG)來查看整個程序。 – xv435 2014-11-05 22:59:46
在問題中內嵌的[mvce](http://stackoverflow.com/help/mcve)比鏈接到異地資源要好。 – jewelsea 2014-11-05 23:01:10