ZBLOG

nodejs websocket

Node.js WebSocket is a protocol that enables two-way communication between client and server over a single, long-lived connection. It allows real-time data exchange between the client and server without the need for polling or continuous HTTP requests.

Node.js provides a built-in module called ws that implements the WebSocket protocol on both the server and client side. With this module, you can easily create a WebSocket server that listens to incoming connections from clients and sends messages back and forth in real time.

Here’s an example of how to create a simple WebSocket server using Node.js:

  1. const WebSocket = require('ws');
  2. const wss = new WebSocket.Server({ port: 8080 });
  3. wss.on('connection', function connection(ws) {
  4. console.log('Client connected');
  5. ws.on('message', function incoming(message) {
  6. console.log(`Received message: ${message}`);
  7. ws.send(`You said: ${message}`);
  8. });
  9. ws.on('close', function close() {
  10. console.log('Client disconnected');
  11. });
  12. });

In this example, we create a new WebSocket.Server instance on port 8080. When a client connects to this server, the connection event is emitted and we log a message to the console.

We also define two event listeners on the WebSocket object (ws) that represents the connection with the client. The first one listens for incoming messages from the client and logs them to the console, as well as sends back a response message using ws.send(). The second one listens for when the connection with the client is closed and logs another message to the console.

Overall, Node.js WebSocket makes it easy to implement real-time communication between clients and servers in your web applications.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=5527

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?