java网络编程
我有两个班;一个是服务器,另一个是客户端,客户端程序接受对服务器的整数写入,然后创建一个游戏对象,然后向客户端返回一个数字,如果返回的数字为0,则游戏停止,否则继续输入整数。下面是代码,问题是,服务器程序只接受1次,然后客户端会抛出一个异常,我认为服务器程序的编码应该有问题
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();
}
}
}
}
# 1 楼答案
可能您需要为
Client
类的main
方法中的每次迭代实例化套接字并获取流(输入和输出)