Java服务器 JavaScript客户端 WebSockets

11

我正在尝试在Java服务器和JavaScript客户端之间建立连接,但是客户端出现了以下错误:

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

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

请问有人能告诉我这里出了什么问题吗?

服务器

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

客户

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

一切似乎都没问题...或许尝试另一个端口?比如12000或更高的端口,听说有些系统不喜欢低端口号...我只是在猜测,因为我不知道我们设置之间可能有什么区别... - Igor Deruga
好的,但这是在服务器端。在客户端,如果您进入Chrome开发工具的Chrome控制台,WebSocket错误不会出现吗? - agfac
哦,你在问题中说你在服务器端遇到了一个错误...我稍后会尝试一下,在Chrome中告诉你是否出现错误。 - Igor Deruga
我已经编辑了帖子。我对代码进行了一些更改,现在出现的错误不同了。谢谢。 - agfac
你检查过本地计算机防火墙是否允许该端口了吗? - Maytham Fahmi
显示剩余6条评论
1个回答

13

首先,你的代码看起来与Java和JavaScript的代码相同。它们都可以实现它们设计的功能,但事实上,你正在尝试将WebSocket客户端连接到Socket服务器。

据我所知,这方面它们是两个不同的事物,参考答案

我从未尝试过你的方法。话虽如此,如果我有一个使用socket的网络应用程序,那么它将是纯客户端/服务器套接字,如果它是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();
你可能需要修改你的代码来适应这个实现,但这应该是工作的一部分。
这里是两个测试的测试输出:
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>

链接到 WebSocket


那个网站已经关闭了。还有其他地方可以找到那个API吗?@maytham-ɯɐɥʇʎɐɯ 谢谢! - Jared Scarito
1
@JaredScarito 这是链接 https://github.com/TooTallNate/Java-WebSocket 我不知道为什么网站挂了,但如果你使用Maven,它会让你的一天更加顺畅。祝好运! - Maytham Fahmi
1
@maytham-ɯɐɥʇʎɐɯ 你太棒了!非常感谢! - Jared Scarito
1
我已经为此苦苦挣扎了好几天。谢谢! - mcool

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接