試圖通過套接字發送arrayList,在對象輸入流初始化(客戶端)處獲取空指針異常。當通過套接字接收數組列表時發生NullPointerException
客戶:
try {
ObjectInputStream objIn = new ObjectInputStream(
Client.socket.getInputStream()); // HERE
library = (ArrayList<Book>) objIn.readObject();
} catch (IOException e) {
服務器:
try {
ObjectOutputStream objOut = new ObjectOutputStream(
this.client.getOutputStream());
objOut.writeObject(library);
objOut.flush(); // added later, not helping
}
我一直在努力,現在幾乎沒有成功comunicate通過套接字兩天。我不知道發生了什麼事。 Ofc我計劃更好地記錄自己,當我有更多的時間,但現在我真的很想知道發生了什麼。
編輯
public class Client {
private static int port = 6666;
private static Socket socket = null;
public Client (int port) {
Client.port = port;
}
public Client() {
}
public void establishConnection() {
try {
Client.socket = new Socket(InetAddress.getByName(null), Client.port);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
服務器:
public void start() {
(new Thread() {
public void run() {
try {
Server.socket = new ServerSocket(Server.portNumber);
while (!Server.stop) {
Socket client = Server.socket.accept();
(new HandleRequest (client)).start();
}
...............
public class HandleRequest extends Thread {
private Socket client = null;
private SQL sql_db = new SQL();
public HandleRequest (Socket client) {
this.client = client;
}
@Override
public void run() {
try {
if (!this.sql_db.isConnected())
this.sql_db.connect();
if (this.client == null) {
System.out.println("Error: client does not exist, NO idea what's going on");
return;
}
ArrayList<Book> library = this.sql_db.getAllBooks();
try {
ObjectOutputStream objOut = new ObjectOutputStream(
this.client.getOutputStream());
objOut.writeObject(library);
objOut.flush();
} catch (Exception e) {
System.out.println("Server error in handling request for whole library!");
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
沒有足夠的代碼在這個問題上給你答案。請告訴我們'Client.socket'的定義和實例。最好張貼證明問題的[SSCCE](http://sscce.org)。 –
您可以提供堆棧跟蹤並顯示其投訴的行號嗎?這通常在這些情況下非常有用。 – CodeChimp
@Duncan Ok會嘗試。 @CodeChimp,堆棧跟蹤在我的代碼中指向'// here' – Kalec