无法将客户端 (Javascript) 连接到现有套接字服务器



我有一个在端口6868上侦听的现有套接字服务器。它是用Java编写的。

我需要将客户端连接到服务器。在我的React应用程序中,客户端是用Javascript编写的。

我已经尝试了我在互联网上找到的几乎所有可能的教程组合,但我仍然无法让客户端连接。

import * as io from "socket.io-client";
export default () => {
// eslint-disable-next-line no-restricted-globals
self.onmessage = (message) => {
const data = message.data;
try {
var socket = io("http://localhost:6868/");
} catch (error) {
console.log("do nothing: " + error);
}
};
};

不管怎样,我都会得到相同的错误:ReferenceError: socket_io_client__WEBPACK_IMPORTED_MODULE_0___default is not defined

这是我在package.json:"socket.io-client": "^4.4.0"中使用的版本

我用以下命令安装了它:npm i socket.io-client

发现socket.io不能用于连接到我在Java中拥有的ServerSocket。为了解决这个问题,我将ServerSocket更改为WebSocketServer

以下是使JavaWebSocket与JavaScript客户端连接所需的所有代码:

WebsocketServer.java

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Set;
public class WebsocketServer extends WebSocketServer {
private static int TCP_PORT = 6868;
private static Set<WebSocket> conns;

public WebsocketServer() {
super(new InetSocketAddress(TCP_PORT));
conns = new HashSet<>();
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
conns.add(conn);
conn.send("hello!!");
System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
conns.remove(conn);
System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("Message from client: " + message);
for (WebSocket sock : conns) {
sock.send("SENDING BACK" + message);
}
}
@Override
public void onError(WebSocket conn, Exception ex) {
//ex.printStackTrace();
if (conn != null) {
conns.remove(conn);
// do some thing if required
}
System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
public static Set<WebSocket> getConns() {
return conns;
}
}

并使用new WebsocketServer().start();main()启动服务器

client.js

var connection = new WebSocket("ws://127.0.0.1:6868");
connection.onopen = function () {
console.log("Connected!");
connection.send("Ping"); // Send the message 'Ping' to the server
};
// Log errors
connection.onerror = function (error) {
console.log("WebSocket Error " + error);
};
// Log messages from the server
connection.onmessage = function (e) {
console.log("Server: " + e.data);
};

Java Web套接字的依赖项:

<dependency>
<groupId>
org.java-websocket
</groupId>
<artifactId>
Java-WebSocket
</artifactId>
<version>
1.3.0
</version>
</dependency>

最新更新