在开发业务系统的时候,根据开发人员不同的技术栈,会使用不同的技术来开发微服务。本文是基于NodeJS提供的websocket的服务。在websocket通过分片的方式将字符串进行切割传递。
server.js:
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (socket) => {
console.log('Client connected');
// 模拟分片传输
var message = 'Hello, WebSocket!数据映射的方式有两种:';
console.log(message.length);
const chunkSize = 5;
const totalChunks = Math.ceil(message.length / chunkSize);
for (let i = 0; i < totalChunks; i++) {
const start = i * chunkSize;
const end = i === totalChunks - 1 ? message.length : start + chunkSize;
const chunk = message.slice(start, end);
socket.send(chunk);
console.log(`Sending chunk ${i + 1}/${totalChunks} - ${chunk}`);
}
socket.on('close', () => {
console.log('Client disconnected');
});
});
console.log('Server is running on port 8080');
client.js:
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080');
ws.on('open', () => {
console.log('连接已建立');
// 发送握手请求
ws.send(
JSON.stringify({
Upgrade: 'websocket',
Connection: 'Upgrade',
//Sec_WebSocket_Accept: createSecWebSocketAccept(ws),
})
);
// 发送分片消息
const message = 'Hello, WebSocket!';
const parts = chunk(message, 1024);
parts.forEach((part, index) => {
ws.send(JSON.stringify({ type: 'split', parts: [part], index: index }));
});
// 接收响应
ws.on('message', (message) => {
//const data = JSON.parse(message);
//if (data.type === 'response') {
console.log('接收到的响应:', message);
//}
});
// 关闭连接
ws.on('close', () => {
console.log('连接已关闭');
});
});
function chunk(str, size) {
const chunks = [];
for (let i = 0; i < str.length; i += size) {
chunks.push(str.slice(i, i + size));
}
return chunks;
}
function createSecWebSocketAccept(ws) {
const key = ws.url.split('=').pop();
const AcceptKey = WebSocket.createSecureContext().SecureSocket.prototype.sec_websocket_accept;
return AcceptKey.replace('$WS_KEY$', key);
}
1>、启动server.js
执行命令:
node server.js
运行效果:
2>、启动client.js
执行命令:
node client.js
运行效果:
客户端:
服务端:
Nodejs提供http服务,参考如下案例:
const http = require("http");
const hostname = "127.0.0.1";
const port = 3000;
//创建HTTP服务器,并提供两个对象,一个请求(http.IncomingMessage对象)和一个
//响应(http.ServerResponse对象)
const server = http.createServer((req, res) => {
res.statusCode = 200;//设置statusCode属性为200,以表相应成功
res.setHeader("Content-Type", "text/plain");//设置Content-Type响应头
res.end("Hello World1111\n");//关闭响应,添加内容作为end()的参数
})
//服务器启动监听
server.listen(port, hostname, () => {
console.log(`服务器运行在http://${hostname}:${port}/`);
})