如何从客户端(Java,套接字)接收特定消息时返回自动响应

时间:2017-10-27 17:19:02

标签: java sockets tcp server client

如果我的客户端向我发送消息“Hello mr server”,我基本上是试图从我的服务器回复。但事实并非如此。

这是我的代码:

public class Server {

    public static final int PORT = 6666;

    public static void main(String[] args) throws IOException {
        new Server().runServer();
    }

    public void runServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("Server up and ready for connections.....");
        while (true) {
            Socket socket = serverSocket.accept();

            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //for fetching data
            String str = br.readLine(); //for fetching data

            System.out.println("Client Data:" + str + '\n');


            String dataSendingToClient = "gg";
            OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream()); //for sending data
            PrintWriter out = new PrintWriter(os); //for sending data
            out.println(dataSendingToClient);
            os.flush();



            if (br.equals("hey mr server")){
                OutputStreamWriter os2 = new OutputStreamWriter(socket.getOutputStream()); //for sending data
                PrintWriter out2 = new PrintWriter(os); //for sending data
                out2.println("hey mr client");
                os.flush();
            }

        }
    }

}

1 个答案:

答案 0 :(得分:0)

您使用的br.equals("hey mr server")始终返回false,因为br不是字符串,而是BufferedReader

相反,您应该使用已定义的str变量str.equals("hey mr server")

另请注意,使用当前代码,服务器只会从客户端读取一条消息,然后再转到下一个连接

如果您希望服务器从单个客户端读取更多消息,则需要循环直到客户端发送断开连接消息/套接字关闭

while(true)
{
    Socket socket = serverSocket.accept();
    BufferedReader br = [...];
    PrintWriter out = [...];

    for(String message = br.readLine(); message != null; message = br.readLine())
    {
        //do stuff
        //message is each line from the client
    }
}

如果您有多个客户端尝试连接,则需要多线程连接

我建议使用一个类来包含连接详细信息,并使用Stacks来轮询客户端是否发送了数据

public static void main(String[] args) //or whatever other method you're running in
{
    List<Connection> clients = new ArrayList<Connection>(); //some data structure to hold the clients

    //start accepting connections
    new Thread(new Runnable()
        {
            public void run()
            {
                while(true)
                    Connection client = new Connection(serverSocket.accept());
            }
        }).start();

    //do something with the clients, read/write/whatever
}

private class Connection extends Runnable
{
    private BufferedReader reader;
    private PrintWriter writer;
    private Queue<String> messages;

    public Connection(Socket s)
    {
        reader = [...];
        writer = [...];
        messages = new LinkedList<String>();
    }

    public void run()
    {
        //just keep reading
        while(true)
            messages.add(reader.readLine();
    }

    public String read()
    {
        messages.poll();
    }

    public void write(String msg)
    {
        writer.write(msg);
        writer.flush();
    }
}

注意:将其作为粗糙的伪代码