I have a Java server set-up for an app I'm making. The Java server takes new clients as they attempt to connect:
//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();
}
On Android, I just use the Socket class and I have no problems. It connects to the endpoint of my Java server running on EC2 on AWS and I have no problems. However, with iOS, from what I've found, 3rd-party libraries come very recommended and I've settled on using Starscream (for the moment).
I can't get the simple connection example to work (the one on the Starscream github page). There are tutorials such as this that set-up a local server with Node.js but I'd rather not get into that as I already have a server that' fairly simple anyway.
Here's my swift code:
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
and it outputs:
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
Is there some kind of problem with connecting from Starscream WebSockets to a Java ServerSocket? I've read bits of things that suggest such problems in others' cases, but I barely know anything about the underlying implementation of sockets.
Your server does not appear to have implemented the WebSockets protocol.
A WebSocket is not simply a TCP connection; it uses a specific HTTP-based handshake, and adds framing to the stream. It's possible to implement this yourself, but I'd advise you to use a library instead if possible -- there are a number of perfectly good implementations available.