我正在嘗試創建一個客戶端可以向服務器發送一些int
值的應用程序(帶遊戲),直到未達到某個值,客戶端可以與服務器進行交換,然後將值發回。TCP服務器和客戶端:服務器響應客戶端時引發IOException
我的第一堂課是TCP應用程序的服務器。在這裏我有一個main()
方法,直到遊戲結束。運行以從客戶端獲取對象的getMoveFromClient()
方法,以及將對象發送到客戶端的sendRequestToClient(Game g, int reponse)
。這裏是代碼:
public static void main(String[] args) {
serverLife = true;
cm = new ConnectionManagerServer(); // this one instanciates my Server options
Game g;
while (serverLife) { // boolean value that allows me to continue over
g = getMoveFromClient(); // get data from client, here every thing is ok
sendRequestToClient(g, 1); // send data to client, here it crashes.
serverLife = g.life; // the object has a parameter that tells if the value is reached or not. (end of the game)
}
}
public static Game getMoveFromClient() {
// this method get data from clients, and works fine.
}
直到這裏,一切都好。但是用這種方法,將數據發送到客戶端:
private static void sendRequestToClient(Game g, int reponse) {
try {
g.setResponse(reponse);
OutputStream out = cm.socket.getOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(out)) {
oos.writeObject(g);
oos.flush();
oos.close();
}
} catch (IOException ex) {
System.out.println("OutpuStreamError : " + ex.getMessage());
}
}
我有以下錯誤:OutpuStreamError : Software caused connection abort: socket write error
另一方面,在客戶端上我有幾乎相同的代碼,直到工作正常對象遊戲應返回:
public static Game getRequestFromServer() {
Game g = null;
try {
InputStream in = mc.socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(in);
g = (Calcul) ois.readObject();
} catch (IOException ex) {
System.out.println("error reception" + ex.getMessage());
} catch (ClassNotFoundException ex) {
System.out.println("erreur lecture de l'objet" + ex.getMessage());
}
return jeu;
}
我有以下錯誤:error reception : Socket is closed
我有一個類爲我的遊戲對象和另外兩個來處理客戶端和服務器的連接端口和套接字。
public ConnectionManagerServer() {
try {
this.serverPort = 6464;
this.serverSocket = new ServerSocket(this.serverPort);
this.socket = this.serverSocket.accept();
} catch (IOException ex) {
System.out.println("serverSocket probleme d'initialisation : " + ex.getMessage());
}
}
,第二個:
public ConnectionManagerClient() {
try {
this.hostAdress = InetAddress.getByName("localhost"); // adresse du serveur
this.serverPort = 6464;
this.socket = new Socket(this.hostAdress, this.serverPort);
} catch (UnknownHostException ex) {
System.out.println("Erreur d'initalisation de l'adresse de l'hote : " + ex.getMessage());
} catch (IOException ex) {
System.out.println("Erreur d'initalisation de la connexion : " + ex.getMessage());
}
}
什麼我不明白的是,當我嘗試從客戶端發送到服務器,它工作正常,並且服務器能夠讀對象內容,但是當我嘗試從服務器發送給客戶端時,我無法從服務器讀取對象。是否因爲我沒有打開插座?
編輯: 我一定要使用accept()
在我的客戶端類從服務器獲取數據?這是錯誤的。