我正在写一个客户机-服务器聊天应用程序。我可以连接他们,我可以发送和接收第一条消息。但我不能送第二个。我试图添加do…while()语句来进行重复,但不起作用。有人能帮我解决这个问题吗?非常感谢这是我的服务器类
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(4999);
Socket serverSocket = server.accept();
System.out.println("client is connected");
String messIn = "", messOut = "";
InputStreamReader serverInput = new InputStreamReader(serverSocket.getInputStream());
BufferedReader serverBufIn = new BufferedReader(serverInput);
Scanner serverScanner = new Scanner(System.in);
PrintWriter serverWriter = new PrintWriter(serverSocket.getOutputStream());
do {
messIn = serverBufIn.readLine();
System.out.println("client : " + messIn);
messOut = serverScanner.nextLine();
serverWriter.print(messOut);
serverWriter.flush();
} while (messOut.equals("quit"));
serverSocket.close();
serverWriter.close();
}
}`
This my client class
`import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
Socket clientSocket = new Socket(InetAddress.getLocalHost(), 4999);
System.out.println("You are connected. Say something!");
String messIn = "", messOut = "";
InputStreamReader clientInput = new InputStreamReader(clientSocket.getInputStream());
BufferedReader clientBufIn = new BufferedReader(clientInput);
Scanner clientScanner = new Scanner(System.in);
PrintWriter clientWriter = new PrintWriter(clientSocket.getOutputStream());
do {
messOut = clientScanner.nextLine();
clientWriter.println(messOut);
clientWriter.flush();
messIn = clientBufIn.readLine();
System.out.println("server : " + messIn);
} while (messOut.equals("quit"));
clientSocket.close();
clientWriter.close();
}
}
`
1条答案
按热度按时间yi0zb3m41#
尝试
while (true) { }
我的代码: