javascript 如何将 udp 发送到 udp node.js 服务器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7451522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:10:39  来源:igfitidea点击:

How to send udp to udp node.js server?

javascripthtmlnode.jsudp

提问by Derek

I'm very new to this so I really don't know what I'm doing, but I've setup a node.js udp server. I want to send a packet to it from the client (being from a website), but I don't know how to do that in javascript/ or if it's even possible. I'm not looking on how to send a packet from a node.js client to server, but rather how to write a website to send a packet to a node.js udp server. Not sure if that made sense, but thanks for the help!

我对此很陌生,所以我真的不知道我在做什么,但我已经设置了一个 node.js udp 服务器。我想从客户端(来自网站)向它发送一个数据包,但我不知道如何在 javascript/ 中做到这一点,或者甚至可能。我不是在研究如何将数据包从 node.js 客户端发送到服务器,而是如何编写网站以将数据包发送到 node.js udp 服务器。不确定这是否有意义,但感谢您的帮助!

回答by phihag

You cannot send UDP datagrams from a webbrowser (i.e. JavaScript). What you can do is contact a webserver (for example via AJAX or websocket) and execute a server-side program (in php or node.js or so) to send the UDP datagram. You can send a UDP datagram with the server-side programming language's native socket module (Python, php, node.js).

您不能从网络浏览器(即 JavaScript)发送 UDP 数据报。您可以做的是联系网络服务器(例如通过 AJAX 或 websocket)并执行服务器端程序(在 php 或 node.js 等中)以发送 UDP 数据报。您可以使用服务器端编程语言的本机套接字模块(Pythonphpnode.js)发送 UDP 数据报。

However, why are you using UDP in the first place? You'll have to handle retransmissions, reordering and the like, and since webbrowsers can only talk via TCP, you're not getting any of the advantages of UDP.

但是,您为什么首先使用 UDP?您将不得不处理重传、重新排序等问题,而且由于网络浏览器只能通过 TCP 进行通信,因此您无法获得 UDP 的任何优势。

回答by Jonathan Dumaine

You may be interested in this tutorial:

您可能对本教程感兴趣:

http://fzysqr.com/2011/02/28/nodechat-js-using-node-js-backbone-js-socket-io-and-redis-to-make-a-real-time-chat-app/

http://fzysqr.com/2011/02/28/nodechat-js-using-node-js-backbone-js-socket-io-and-redis-to-make-a-real-time-chat-app/

It goes through how to create a chat application in node.js in very fine detail, he even shows how to use Socket.io (a browser js library) to utilize web sockets for realtime, low latency responses.

它非常详细地介绍了如何在 node.js 中创建聊天应用程序,他甚至展示了如何使用 Socket.io(一个浏览器 js 库)来利用 Web 套接字进行实时、低延迟响应。

And as Phihag hinted at, UDP isn't good for this sort of application because UDP does not guarantee your packet will get to its destination. You definitely want to use TCP Sockets in this case.

正如 Phihag 所暗示的,UDP 不适合这类应用程序,因为UDP 不能保证您的数据包会到达目的地。在这种情况下,您肯定想使用 TCP 套接字。

More reading:

更多阅读: