0
我有兩個類;一個是服務器,另一個是客戶端,客戶端程序接受一個整數寫入服務器,而不是創建一個遊戲對象,然後返回一個數字給客戶端,如果返回的數字是0,遊戲停止,否則繼續輸入一個整數。以下是代碼,問題是,服務器程序只接受1次,然後客戶端會拋出一個異常,我認爲應該有一個服務器程序的編碼問題。java網絡編程
server.java
import java.io.*;
import java.net.*;
class ClientHandler extends Thread {
Socket socket;
Game g;
public ClientHandler(Socket socket) {
this.socket = socket;
g = new Game(50);
}
public void run() {
try {
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
int x = dis.readInt();
int reply = this.g.guess(x);
System.out.println(x);
dos.writeInt(reply);
//System.out.println(reply);
//System.out.println(reply);
socket.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
public class Server {
public static void main(String arg[]) {
try {
ServerSocket ss = new ServerSocket(12345);
while(true) {
Socket s = ss.accept();
ClientHandler ch = new ClientHandler(s);
ch.start();
}
}
catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
client.java
import java.util.Scanner;
import java.net.Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class Client {
public static void main(String args[]) {
Socket socket = null;
DataInputStream in = null;
DataOutputStream out = null;
Scanner console = new Scanner(System.in);
int guess;
int result;
try {
socket = new Socket("127.0.0.1", 12345);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
do {
System.out.print("Guess a number: ");
guess = console.nextInt();
out.writeInt(guess);
result = in.readInt();
if (result == 0) {
System.out.println("Correct!");
} else if (result == -1) {
System.out.println("Too small!");
} else if (result == 1) {
System.out.println("Too large!");
} else {
System.out.println("Too many attempts!");
}
} while (result != 0 && result != -2);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
爲什麼服務器在寫入後關閉了套接字?我認爲這是問題。你能發佈異常的完整堆棧跟蹤嗎? – 2011-11-28 04:36:15