我正在尝试创建一个客户端 - 服务器Java应用程序,其中有4个用户连接,但是我在服务器和客户端类之间的通信和消息交换方面存在一些问题。
以下是服务器的代码:
public class Server {
private static final int port = 9991;
private static final String serverHost = "localhost";
private static ServerSocket serverSocket;
private static Socket socket;
private static DataInputStream serverInput;
private static DataOutputStream serverOutput;
private static String message;
private static int noOfUsers = 0;
public static void main(String args[]){
try{
serverSocket = new ServerSocket(port);
System.out.println("Server is up (Port: " + port + ")");
while (true){
socket = serverSocket.accept();
serverInput = new DataInputStream(socket.getInputStream());
serverOutput = new DataOutputStream(socket.getOutputStream());
message = serverInput.readUTF();
if (message.equals("C_Message1")){
System.out.println("Client has connected!");
serverOutput.writeUTF("S_Message1");
}
else if (message.equals("C_Message2")){
if (noOfUsers <= 3){
serverOutput.writeUTF("S_Message2");
noOfUsers++;
}
else {
serverOutput.writeUTF("S_Message3");
System.out.println("User rejected");
}
}
}
} catch (IOException e){
System.err.println(e.getMessage() + " -> " + e.getCause());
}
}
}
这是Client类的代码:
public class Client implements Runnable {
private static final int serverPort = 9991;
private static final String serverHost = "localhost";
private static Socket socket;
private static DataInputStream clientInput;
private static DataOutputStream clientOutput;
private static String message;
private static int userID;
@Override
public void run() {
try {
socket = new Socket(serverHost, serverPort);
System.out.println("Connection succesfull.");
clientInput = new DataInputStream(socket.getInputStream());
clientOutput = new DataOutputStream(socket.getOutputStream());
clientOutput.writeUTF("C_Message1");
System.out.println("Connected to server!");
while (true){
message = clientInput.readUTF();
if (message.equals("S_Message1")){
clientOutput.writeUTF("C_Message2");
}
else if (message.equals("S_Message2")){
System.out.println("Accepted on table!");
}
else if (message.equals("S_Message3")){
System.out.println("Rejected");
}
}
} catch (UnknownHostException e) {
System.out.println("Cannot find host.");
} catch (IOException e) {
System.out.println("IO Exception thrown");
}
}
}
我在GUI类中创建了一个Client实例,
Client client = new Client();
Thread clientThread = new Thread(client);
clientThread.start();
问题是邮件交换无法正常工作。 我将C_Message1从客户端发送到服务器,当服务器收到此消息时,它将S_Message1发送回客户端,然后客户端将C_Message2发送到服务器,依此类推。 但是,当客户端尝试发送C_Message2时,消息交换会以某种方式停止。
答案 0 :(得分:1)
在像这样的客户端服务器系统中,你必须在客户端上处理两个线程(至少),在服务器上处理两个线程:
这是一个异步,基本上如下:
我希望这个过程很清楚。祝你好运