我是Java套接字编程的新手,我制作了一个带有Java套接字的简单客户端/服务器,其中客户端需要输入选项以访问服务器中的函数,但是在服务器发送双倍输入的情况下却遇到了这个问题,但是我只需一个。
有人可以帮助我吗?谢谢。
服务器:
public static void main(String[] args) throws Exception {
try {
ServerSocket server = new ServerSocket(8888);
int counter = 0;
System.out.println("Server Started ....");
while (true) {
counter++;
Socket serverClient = server.accept();
// server accept the client connection request
System.out.println(" >> " + "Client No:" + counter + " started!");
DataInputStream inStream = new DataInputStream(serverClient.getInputStream());
DataOutputStream outStream = new DataOutputStream(serverClient.getOutputStream());
ServerClientThread sct = new ServerClientThread(serverClient, counter, inStream,
outStream);
// send the request to a separate thread
sct.start();
}
} catch (IOException e) {
System.out.println(e);
}
}
class ServerClientThread extends Thread {
final Socket serverClient;
final int clientNo;
final DataInputStream inStream;
final DataOutputStream outStream;
ServerClientThread(Socket inSocket, int counter, DataInputStream inStream,
DataOutputStream outStream) {
this.serverClient = inSocket;
this.clientNo = counter;
this.inStream = inStream;
this.outStream = outStream;
}
@Override
public void run() {
try {
String clientMessage = "", serverMessage = "";
while (!clientMessage.equals("bye")) {
outStream.writeUTF("1,2,3:");
clientMessage = inStream.readUTF();
switch (clientMessage) {
case "1":
outStream.writeUTF("masukkan number:");
outStream.flush();
serverMessage = inStream.readUTF();
outStream.writeUTF(serverMessage);
break;
default:
System.out.println("tidak ada pilihan!");
}
}
inStream.close();
outStream.close();
serverClient.close();
} catch (IOException ex) {
System.out.println(ex);
} finally {
System.out.println("Client -" + clientNo + " exit!! ");
}
}
}
客户:
public static void main(String[] args) throws Exception {
try {
Socket socket = new Socket("127.0.0.1", 8888);
DataInputStream inStream = new DataInputStream(socket.getInputStream());
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String clientMessage = "", serverMessage = "";
while (!clientMessage.equals("bye")) {
System.out.println(inStream.readUTF());
String input = br.readLine();
outStream.writeUTF(input);
}
outStream.close();
outStream.close();
socket.close();
} catch (Exception e) {
System.out.println(e);
}
}
客户端错误:
1,2,3:
1
masukkan number:
12
12
3
1,2,3:
1
1,2,3:
1
masukkan number:
12
1
13
1,2,3:
14
1,2,3:
15
服务器端错误:
Server Started ....
Client No:1 started!
tidak ada pilihan!
tidak ada pilihan!
tidak ada pilihan!
tidak ada pilihan!
tidak ada pilihan!
tidak ada pilihan!
java.net.SocketException: Connection reset
Client -1 exit!!