Reputation: 150
I'm trying to connect javascript with Java, but I'm getting some errors:
Error on the javascript side:
WebSocket connection to 'wss://127.0.0.1:1234/' failed: WebSocket opening handshake timed out
Error on the Java side:
java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:197)
at java.io.DataInputStream.readUTF(DataInputStream.java:609)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at networkingtest.Server.start(Server.java:29)
at networkingtest.NetworkingTest.main(NetworkingTest.java:9)
Here is my javascript code:
var connection;
function init() {
connection = new WebSocket('wss://127.0.0.1:1234/');
connection.onopen = function () {
connection.send('Ping');
};
}
Here is the Java code:
package networkingtest;
import java.io.*;
import java.net.*;
public class Server {
public ServerSocket ss;
public Socket s;
public int port;
public Server(int p) {
port = p;
}
public void start() {
try {
ss = new ServerSocket(port);
s = ss.accept();
DataInputStream di = new DataInputStream(s.getInputStream());
while (true) {
if (s.isConnected()) {
System.out.println(di.readUTF());
} else {
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I cannot see what I am doing wrong. Is it a mistake on the Java side or on the javascript side?
Upvotes: 0
Views: 974
Reputation: 707986
A webSocket is not a plain TCP socket. It has a whole connection scheme, a security scheme and a data format. So, a webSocket client can only talk to a webSocket server. If you try to connect a webSocket client to a non-webSocket server, the client will not see the proper response and will immediately disconnect. The error you see on the client side:
WebSocket opening handshake timed out
is because the client did not see the response it was expecting from the server when it first connected.
You can use a webSocket library with your Java server to implement a webSocket server in your Java code.
Upvotes: 1