我在比较从客户端发送到服务器的字符串时遇到问题。我试图从客户端读取消息“HELLO”,然后从服务器回来问候。我的问题是当我在服务器类中找到我的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(4200);
System.out.println("The Server is waiting for a client on port 4200");
//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);
if(message == "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.*;
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("cmps329.csit.selu.edu", 4200);
//Sends message to the server
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
ps.println("HELLO");
//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);
}
}