Java 服务器 JavaScript 客户端 WebSocket

2023-11-21

我正在尝试在 Java 服务器和 JavaScript 客户端之间建立连接,但我在客户端收到此错误:

与“ws://127.0.0.1:4444/”的 WebSocket 连接失败:连接在收到握手响应之前关闭

它可能会保持在 OPENNING 状态,因为connection.onopen函数从未被调用。这console.log('Connected!')没有被调用。

有人可以让我知道这里出了什么问题吗?

Server

import java.io.IOException;
import java.net.ServerSocket;

public class Server {

    public static void main(String[] args) throws IOException {

        try (ServerSocket serverSocket = new ServerSocket(4444)) {
            GameProtocol gp = new GameProtocol();

            ServerThread player= new ServerThread(serverSocket.accept(), gp);
            player.start();

        } catch (IOException e) {
            System.out.println("Could not listen on port: 4444");
            System.exit(-1);
        }

    }

}

服务器线程

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread extends Thread{

    private Socket socket = null;
    private GameProtocol gp;

    public ServerThread(Socket socket, GameProtocol gp) {
        super("ServerThread");
        this.socket = socket;
        this.gp = gp;
    }

    public void run() {

        try (
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()));
                ) {
            String inputLine, outputLine;

            while ((inputLine = in.readLine()) != null) {
                outputLine = gp.processInput(inputLine);
                System.out.println(outputLine);
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

游戏协议

public class GameProtocol {

    public String processInput(String theInput) {

        String theOutput = null;

        theOutput = theInput;

        return theOutput;
    }
}

Client

var connection = new WebSocket('ws://127.0.0.1:4444');

connection.onopen = function () {
    console.log('Connected!');
    connection.send('Ping'); // Send the message 'Ping' to the server
};

// Log errors
connection.onerror = function (error) {
    console.log('WebSocket Error ' + error);
};

// Log messages from the server
connection.onmessage = function (e) {
    console.log('Server: ' + e.data);
};

首先,您的代码看起来与 Java 和 JavaScript 代码相同。两者都按其设计目的工作,但事实是您正在尝试将 WebSocket 客户端连接到套接字服务器。

据我所知,在这方面它们是两件不同的事情answer.

我从来没有尝试过你的方法。也就是说,如果我有一个使用套接字的网络应用程序,那么它将是纯客户端/服务器套接字,如果它是一个 Web 应用程序,那么我也会在两侧使用 WebSocket。

到目前为止,一切都很好..

为了使这项工作顺利进行,这个答案建议在服务器端使用任何可用的 WebSocket,您的问题就可以解决。

我在用Java 的 WebSocket这是一个示例实现,我已经使用您的客户端代码进行了测试,并且它在客户端和服务器端都有效。

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Set;

public class WebsocketServer extends WebSocketServer {

    private static int TCP_PORT = 4444;

    private Set<WebSocket> conns;

    public WebsocketServer() {
        super(new InetSocketAddress(TCP_PORT));
        conns = new HashSet<>();
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conns.add(conn);
        System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        conns.remove(conn);
        System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("Message from client: " + message);
        for (WebSocket sock : conns) {
            sock.send(message);
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        //ex.printStackTrace();
        if (conn != null) {
            conns.remove(conn);
            // do some thing if required
        }
        System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }
}

在你的主要方法上:

new WebsocketServer().start();

您可能需要操作您的代码以使其适合此实现,但这应该是工作的一部分。

这是 2 个测试的测试输出:

New connection from 127.0.0.1
Message from client: Ping
Closed connection to 127.0.0.1
New connection from 127.0.0.1
Message from client: Ping

这是 WebSocket maven 配置,否则手动下载 JAR 文件并将其导入到您的 IDE/开发环境中:

<!-- https://mvnrepository.com/artifact/org.java-websocket/Java-WebSocket -->
<dependency>
    <groupId>org.java-websocket</groupId>
    <artifactId>Java-WebSocket</artifactId>
    <version>1.3.0</version>
</dependency>

Link to WebSocket.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 服务器 JavaScript 客户端 WebSocket 的相关文章

随机推荐