我为我正在制作的应用程序设置了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类,我没有问题。它连接到我在AWS上的EC2上运行的Java服务器的端点,我没有任何问题。但是,对于iOS,我发现第三方库非常推荐,我已经决定使用Starscream(目前)。
我无法使用简单的连接示例(Starscream github页面上的那个)。有this这样的教程用Node.js设置本地服务器,但是我不想进入那个,因为我已经拥有了一台服务器。相当简单。
这是我的快捷代码:
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是否存在某种问题?我已经阅读了一些在其他人身上发现此类问题的事情。但是我对套接字的底层实现几乎一无所知。
答案 0 :(得分:1)
您的服务器似乎没有实施the WebSockets protocol。
WebSocket 不只是一个TCP连接;它使用特定的基于HTTP的握手,并为流添加框架。可以implement this yourself,但我建议您尽可能使用库 - 有a number of perfectly good implementations available。