如何在服务器端创建应该给出一些响应的监听器?

时间:2015-06-05 11:27:05

标签: java spring websocket spring-boot

您好我正在使用spring boot构建项目并使用套接字编程在客户端和服务器之间进行通信。我已经在localhost上启动了我的项目,端口号为8080。 我使用以下代码运行我的客户端程序:

String serverName = "localhost";
        int port = 8080;
        try {
            System.out.println("Connecting to " + serverName + " on port "
                    + port);
            Socket client = new Socket(serverName, port);
            System.out.println("Just connected to "
                    + client.getRemoteSocketAddress());
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);
            System.out.println("Hello from " + client.getLocalSocketAddress());
            out.writeUTF("Hello from " + client.getLocalSocketAddress());
            InputStream inFromServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            System.out.println("Server says " + in.readUTF());
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

此程序打印消息“Just connected to 127.0.0.1:8080”但在“client.close”上方的行引发异常:

Connecting to localhost on port 8080
Just connected to localhost/127.0.0.1:8080
Hello from /127.0.0.1:37281
java.io.EOFException
    at java.io.DataInputStream.readFully(DataInputStream.java:197)
    at java.io.DataInputStream.readUTF(DataInputStream.java:609)
    at java.io.DataInputStream.readUTF(DataInputStream.java:564)
    at com.oodles.Demo.App.main(App.java:39)

我的要求是如何在服务器端创建监听器,它可以处理来自客户端的消息并发回一些响应

2 个答案:

答案 0 :(得分:0)

我检查你的代码。连接正常,但是当你使用in.readUTF()时客户端没有响应服务器;

您可以使用以下代码:

String serverName =“localhost”;         int port = 8080;

    try {
        System.out.println("Connecting to " + serverName + " on port "
                + port);
        Socket client = new Socket(serverName, port);
        System.out.println("Just connected to "
                + client.getRemoteSocketAddress());
        OutputStream outToServer = client.getOutputStream();
        DataOutputStream out = new DataOutputStream(outToServer);
        System.out.println("Hello from " + client.getLocalSocketAddress());
        out.writeUTF("Hello from " + client.getLocalSocketAddress());
        InputStream inFromServer = client.getInputStream();
        DataInputStream in = new DataInputStream(inFromServer);

        if (in.read() != -1) {
            System.out.println("Server says " + in.readUTF());
        }

        client.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

由于spring boot在tomcat上运行,而tomcat只能理解HTTP。所以这里你的客户端连接到tomcat服务器,它只能理解HTTP。因此,如果您想通过HTTP连接到spring-boot app,则通过TCP连接将HTTP请求发送到spring-boot应用程序。否则,在spring-boot应用程序上实现一个组件,该组件可以接受某些其他端口上的TCP连接,并按照您的协议进行处理。