node.js - 服务器中的 Socket.io 反复断开连接,而在客户端却没有
问题描述
我打算制作一个像 WhatsApp 这样的私人聊天应用程序。我成功连接到服务器,但几秒钟后套接字与服务器断开连接。在客户端上它不会断开连接。
服务器代码:
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
const onlineusers = {};
const socketid = {};
io.on('connection', cs => {
cs.on('online', username => {
if(username){
onlineusers[username] = cs.id;
socketid[cs.id] = username;
}
console.log("\nonline: ", onlineusers);
});
cs.on('disconnect', () => {
delete onlineusers[socketid[cs.id]];
console.log("\noffline: ", onlineusers);
});
});
const chat = io.of("/chat");
chat.on('connection', cs => {
cs.on('startchat', username => {
if (username){
chat.to('/chat#'+onlineusers[username]).emit('hey', 'I love programming');
}
});
});
server.listen(port, err => {
if(err){
console.error("Some Error: "+err);
}else{
console.log(`Server is running on port: ${port}`);
}
});
我的客户代码是由 react-native 和 socket.io-client 编写的:
在线用户文件:
import io from 'socket.io-client';
const SocketEndpoint = 'http://192.168.43.172:3000';
this.socket = io(SocketEndpoint, {
transports: ['websocket']
});
this.socket.on('connect', () => {
if (this.state.username) {
this.socket.emit("online", this.state.username);
}
});
this.socket.on('connect_error', (err) => {
Alert.alert(err);
});
this.socket.on('disconnect', () => {
Alert.alert('disconnected');
});
聊天页面文件:
import io from 'socket.io-client';
const SocketEndpoint = 'http://192.168.43.172:3000/chat';
this.socket = io(SocketEndpoint, {
transports: ['websocket']
});
this.socket.on('connect', () => {
if (theirusername) {
this.socket.emit('startchat', theirusername);
}
this.socket.on('hey', data => {
alert(data);
});
this.socket.on('janajan', data => {
alert(data);
});
});
我想保留服务器上的客户端套接字,直到客户端自己断开连接。因为在这里当我想说嘿时它会断开连接,我的消息可以传递给客户端。之前谢谢你
解决方案
推荐阅读
- sonarqube - 如何在 SonarQube 中配置高可用性
- angularjs - AngularJS:旧版本的 ng-option 禁用
- javascript - Javascript - 从数组中检索随机图像
- javascript - 我如何使用 reactjs 回调函数
- angular - 在 Angular 模块中注册泛型类型声明
- oracle - 如何根据表名作为输入在 PL/Sql 中动态创建记录
- excel - VBA代码根据原点自动着色文本
- d3.js - D3 可视化未启动
- jquery - 如何将数据表中 columnDefs 的目标定义为“最后一个”?
- javascript - InversifyJS - 注入服务来表达中间件