node.js WebSocket
时间: 2023-12-08 11:37:43 浏览: 81
node.js websocket
4星 · 用户满意度95%
Node.js原生API没有提供对WebSocket的支持,需要安装第三方包才能使用WebSocket功能。可以使用ws模块来实现WebSocket功能。以下是一个简单的例子,演示如何创建WebSocket服务器和客户端:
1.创建WebSocket服务器:
```javascript
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', function connection(ws) {
console.log('client connected'); ws.send('Welcome to WebSocket server!');
ws.on('message', function incoming(message) {
console.log('received: %s', message);
ws.send('You said: ' + message);
});
ws.on('close', function close() {
console.log('client disconnected');
});
});
```
2.创建WebSocket客户端:
```javascript
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080');
ws.on('open', function open() {
console.log('connected');
ws.send('Hello, WebSocket server!');
});
ws.on('message', function incoming(data) {
console.log('received: %s', data);
});
ws.on('close', function close() {
console.log('disconnected');
});
```
阅读全文