无法将红蜘蛛 WebSocket 连接到 Java ServerSocket

Can't connect Starscream WebSocket to Java ServerSocket

我为正在制作的应用程序设置了 Java 服务器。 Java 服务器在尝试连接时接收新客户端:

//Continuously accept new user clients
    try(ServerSocket serverSocket = new ServerSocket(portNumber)){ 

        while(!Thread.currentThread().isInterrupted()){

            //I do some stuff here
            ...
            //Then accept the socket
            Socket s = serverSocket.accept();

            //Then I do stuff with s; the user is connected
            ...

        }

    } catch (IOException e) {
        System.err.println("Could not listen on port "+portNumber);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

在 Android 上,我只使用 Socket class,没有任何问题。它连接到我在 AWS EC2 上的 Java 服务器 运行 的端点,我没有遇到任何问题。但是,根据我的发现,iOS 非常推荐使用第 3 方库,因此我决定使用 Starscream(暂时)。

我无法使用简单的连接示例(红蜘蛛 github 页面上的示例)。 this 等教程使用 Node.js 设置本地服务器,但我不想深入了解它,因为我已经有了一个相当简单的服务器。

这是我的 swift 代码:

class ViewVontroller: UIViewController, WebSocketDelegate{
    var socket = WebSocket(url: URL(string: "ec2-12-345-678-910.compute-1.amazonaws.com/:4922/")!)

    override func viewDidLoad(){
        super.viewDidLoad()
        socket.delegate = self

        print("connecting")
        socket.connect()
        print("should've connected")
    }
    ... //The rest of the protocol is implemented below with simple print statements as the body

它输出:

connecting
should've connected
[timestamp/project name...] [] nw_connection_get_connected_socket_block_invoke 1 Connection has no connected handler
Websocket disconnected: The operation couldn't be completed. Operation timed out

从 Starscream WebSockets 连接到 Java ServerSocket 是否存在某种问题?我读过一些在其他案例中暗示此类问题的东西,但我对套接字的底层实现几乎一无所知。

您的服务器似乎没有实现 the WebSockets protocol

WebSocket 不是简单的 TCP 连接;它使用特定的基于 HTTP 的握手,并向流中添加帧。可以 implement this yourself, but I'd advise you to use a library instead if possible -- there are a number of perfectly good implementations available.