将 javascript WebSocket 与 Java ServerSocket 连接 [英] Connect a javascript WebSocket with a Java ServerSocket

查看:71
本文介绍了将 javascript WebSocket 与 Java ServerSocket 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 javascript 与 Java 连接,但出现了一些错误:

I'm trying to connect javascript with Java, but I'm getting some errors:

javascript 方面的错误:

Error on the javascript side:

WebSocket connection to 'wss://127.0.0.1:1234/' failed: WebSocket opening handshake timed out

Java 端的错误:

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)

这是我的 javascript 代码:

Here is my javascript code:

var connection;

function init() {
    connection = new WebSocket('wss://127.0.0.1:1234/');
    connection.onopen = function () {
        connection.send('Ping');
    };
}

Java 代码如下:

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();
        }
    }

}

我看不出我做错了什么.是 Java 端的错误还是 javascript 端的错误?

I cannot see what I am doing wrong. Is it a mistake on the Java side or on the javascript side?

推荐答案

webSocket 不是普通的 TCP 套接字.它具有完整的连接方案、安全方案和数据格式.因此,webSocket 客户端只能与 webSocket 服务器通信.如果您尝试将 webSocket 客户端连接到非 webSocket 服务器,客户端将看不到正确的响应并立即断开连接.您在客户端看到的错误:

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.

您可以在 Java 服务器中使用 webSocket 库,以在 Java 代码中实现 webSocket 服务器.

You can use a webSocket library with your Java server to implement a webSocket server in your Java code.

这篇关于将 javascript WebSocket 与 Java ServerSocket 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆