使用Node.js可以很方便地搭建Websocket服务器,下面就来详细讲解一下具体的步骤。
步骤1:安装依赖
安装websocket和ws模块,这两个模块都可以用于搭建websocket服务器,我们在下面的示例中将演示这两个模块的使用方法。可以使用npm命令进行安装:
npm install websocket
npm install ws
步骤2:创建WebSocket服务器
使用websocket模块搭建websocket服务器的代码如下:
const WebSocketServer = require('websocket').server;
const http = require('http');
const server = http.createServer((req, res) => {
console.log('Received request for ' + req.url);
res.writeHead(404);
res.end();
});
server.listen(8080, () => {
console.log('Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
return true; // 可以设置只允许特定的origin连接
}
wsServer.on('request', (request) => {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log('Connection from origin ' + request.origin + ' rejected.');
return;
}
const connection = request.accept('echo-protocol', request.origin);
console.log('Connection accepted.');
connection.on('message', (message) => {
if (message.type === 'utf8') {
console.log('Received message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
} else if (message.type === 'binary') {
console.log('Received binary message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', (reasonCode, description) => {
console.log('Peer ' + connection.remoteAddress + ' disconnected with reason code: ' + reasonCode + " and description: " + description);
});
});
使用ws模块搭建websocket服务器的代码如下:
const WebSocket = require('ws');
const server = new WebSocket.Server({port: 8080});
console.log('Server is listening on port 8080');
server.on('connection', (socket) => {
console.log('Connection accepted.');
socket.on('message', (message) => {
console.log('Received message: ' + message);
socket.send('Received message: ' + message);
});
socket.on('close', (event) => {
console.log('Connection closed.', event);
});
socket.on('error', (event) => {
console.log('Error:', event);
});
});
在这两个示例中,我们创建了一个WebSocket服务器并且监听端口8080。当有新客户端连接到服务器时,会触发connection事件。这个事件的回调函数中可以处理客户端发来的消息,也可以向客户端发送消息。当客户端断开连接或者出现错误时,会分别触发close事件和error事件。
示例1:使用websocket模块搭建的WebSocket服务器
使用websocket模块搭建的WebSocket服务器可以使用浏览器自带的WebSocket API进行连接和通信,下面是一个简单的示例:
const ws = new WebSocket('ws://localhost:8080', 'echo-protocol');
ws.onopen = () => {
console.log('WebSocket connected.');
ws.send('Hello Server!');
};
ws.onmessage = (event) => {
console.log('Received message: ' + event.data);
};
ws.onclose = (event) => {
console.log('WebSocket disconnected. Code: ' + event.code + ', Reason: ' + event.reason);
};
ws.onerror = (event) => {
console.log('WebSocket error:', event);
};
这段代码会向我们刚才创建的WebSocket服务器发送一条消息'Hello Server!',并在收到服务器的回复时打印消息内容。在此之前,需要在浏览器端引入websocket.min.js库。
示例2:使用ws模块搭建的WebSocket服务器
使用ws模块搭建的WebSocket服务器可以使用第三方库socket.io进行连接和通信,socket.io具有更高级的API,甚至可以自动重连等,下面是一个示例:
const io = require('socket.io-client');
const socket = io('http://localhost:8080');
socket.on('connect', () => {
console.log('Socket connected.');
socket.emit('test', 'Hello Server!');
});
socket.on('message', (data) => {
console.log('Received message: ' + data);
});
socket.on('disconnect', () => {
console.log('Socket disconnected.');
});
socket.on('error', (error) => {
console.log('Socket error:', error);
});
这段代码会向我们刚才创建的WebSocket服务器发送一条消息'Hello Server!',并在收到服务器的回复时打印消息内容。在此之前,需要安装和引入socket.io-client库。
以上就是使用Node.js搭建WebSocket服务器的完整攻略和两个示例的详细讲解,希望对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:用nodejs搭建websocket服务器 - Python技术站