简体   繁体   English

客户端和服务器的Java套接字问题

[英]Java socket issue with client and server

I am having an issue comparing the string that is sent from the client to the server. 我在比较从客户端发送到服务器的字符串时遇到问题。 I am trying to read in the message "HELLO" from the client and then respond with hello back from the server. 我正在尝试从客户端读取消息“ HELLO”,然后从服务器向后打招呼。 My issue is that when I get to my if statement in the server class I am always hitting the else. 我的问题是,当我到达服务器类中的if语句时,我总是会碰到else。 I believe I am having trouble understanding which lines are collecting data or just printing. 我相信我在理解哪些行正在收集数据或仅进行打印时遇到了麻烦。 Going to do some research in the mean time, I want to learn this good. 同时要进行一些研究,我想学习这一点。 Any idea as to why, thank you in advance? 为什么知道,请先感谢您?

Server class: 服务器类:

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");
            }
    }

}

Client class: 客户类别:

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);        
    }

}

Use 采用

if (message.equals("HELLO"))

See How do I compare strings in Java? 请参阅如何比较Java中的字符串? for the why. 为什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM