简体   繁体   English

将字节从 javascript 客户端发送到 java 后端 DatagramSocket

[英]Sending bytes from javascript client to java backend DatagramSocket

I have a java app that functions as a server, listening to some port using the java.net.DatagramSocket class.我有一个用作服务器的 java 应用程序,使用 java.net.DatagramSocket 类监听某个端口。 The server is able to receive packets from some other java clients.服务器能够接收来自其他一些 java 客户端的数据包。 What I did not manage to do is have a javascript client to the server.我没有设法做的是在服务器上有一个 javascript 客户端。 I've tried sending messages as WebSocket client我尝试将消息作为 WebSocket 客户端发送

    const ws = new WebSocket("ws://localhost:9999");
    ws.addEventListener("open", () => {
        console.log("CONNECTED")
    })

But I'm getting the following error in the browser console:但是我在浏览器控制台中收到以下错误:

App.js:9 WebSocket connection to 'ws://localhost:9999/' failed: App.js:9 WebSocket 连接到 'ws://localhost:9999/' 失败:

I've also tried using net library to send message:我也尝试过使用网络库发送消息:

    const net = require("net");
    const options = {
        post: 9999
    };
    const  client = net.createConnection(options);
    client.write("TEST")

But I'm getting the following error:但我收到以下错误:

Uncaught TypeError: net.createConnection is not a function未捕获的类型错误:net.createConnection 不是函数

Is there any other way to do this?有没有其他方法可以做到这一点?

UDP (DatagramSocket) and WebSocket are totally different things. UDP (DatagramSocket) 和 WebSocket 是完全不同的东西。 WebSocket is a protocol on top of HTTP which is on top of TCP. WebSocket 是 HTTP 之上的协议,它位于 TCP 之上。

In JavaScript running inside the browser you cannot send UDP packages.在浏览器内运行的 JavaScript 中,您不能发送 UDP 包。

You can write some kind of a proxy server, which can receive messages via WebSocket from your JavaScript program and send them via UDP to your server.您可以编写某种代理服务器,它可以通过 WebSocket 从您的 JavaScript 程序接收消息,并通过 UDP 将它们发送到您的服务器。

Or extend your server with a WebSocket interface.或者使用 WebSocket 接口扩展您的服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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