입력을 입력 할 때 루프가 실패하는 동안 클라이언트에서 입력을 읽는 데 문제가 있습니다. 서버 클래스에서 while 문을 사용하지 않고 if 문을 사용할 때마다 완벽하게 작동합니다. 아무도 왜 이것이 실패 할 수 있는지를 지적 해 줄 수 있습니까?소켓 읽기가 자바에서
서버 클래스 :
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception
{
Server myServer = new Server();
myServer.run();
}
public void run() throws Exception
{
//Initializes the port the serverSocket will be on
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("The Server is waiting for a client on port 9999");
//Accepts the connection for the client socket
Socket socket = serverSocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
//Confirms that the message was received
System.out.println(message);
//When this while is here. The match fails and it goes to the else statement.
//Without the while statement it will work and print "Received our hello message."
//when the client says HELLO.
while(message != null)
{
if(message.equals("HELLO"))
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Received our hello message.");
}
else
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Did not receive your hello message");
}
}
}
}
클라이언트 클래스 : 당신이 무한 루프 그래서
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception
{
Client myClient = new Client();
myClient.run();
}
public void run() throws Exception
{
Socket clientSocket = new Socket("localhost", 9999);
//Sends message to the server
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
Scanner scan = new Scanner(System.in);
String cMessage = scan.nextLine();
ps.println(cMessage);
//Reads and displays response from server
InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
System.out.println(message);
}
}
무엇이 작동하지 않습니까? 나는 당신의 코드를 컴파일하고 "안녕하세요 메시지를 받았습니다." 클라이언트에 HELLO를 입력 한 후 –
while 루프를 꺼낼 때 작동합니다. 내가 HELLO를 받아서 서버 창에 출력 할 때 아무것도 남기지 않으면 예외가 생깁니다. – Shawn
좋은 연습은 프로그램 끝에서 모든 소켓과 독자를 닫는 것입니다. –