简体   繁体   中英

Connect a javascript WebSocket with a Java ServerSocket

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM