【发布时间】:2020-04-13 08:57:02
【问题描述】:
我对 TCP 和服务器连接相关的问题非常陌生。我的任务是实现一个功能来检查连接到我们服务器的用户端口是打开还是关闭,以确定何时在前端向他们显示消息,通知他们端口的状态。
经过这么多研究,我仍然无法弄清楚如何建立这种连接,该功能需要在前端运行,这使得它更加困难。我已经尝试在后端实现相同的功能,并且能够通过npm package 实现我想要的。但是由于这个包依赖于 NodeJs 的net 包,所以我不能在客户端使用它。
我继续使用 WebSockets 甚至是图像实现一些自定义功能,但是浏览器总是给我一个 net:: ERR_EMPTY_RESPONSE 错误,而不是获取连接状态。
以下是我迄今为止编写的一些代码,用于尝试找出问题所在。 我真的很感激被指出正确的方向。谢谢
export const checkSocketIoConnect = (url, timeout) => {
return new Promise(function(resolve, reject) {
let errAlready = false;
timeout = timeout || 50000;
let socket = io(url, {
transport: ['websocket'],
reconnection: true, timeout: timeout, reconnectionDelay: 1000,
reconnectionAttempts: 50,
rejectUnauthorized: false
});
// success
socket.on('connect', function() {
console.log('connecting succesfulyy');
clearTimeout(timer);
resolve();
socket.close();
});
// set our own timeout in case the socket ends some other way than what we are listening for
let timer = setTimeout(function() {
console.log('timer');
timer = null;
error('local timeout');
}, timeout);
// common error handler
const error = (data) => {
console.log('errrror');
if (timer) {
clearTimeout(timer);
timer = null;
}
if (!errAlready) {
errAlready = true;
reject(data);
socket.disconnect();
}
};
// errors
socket.on('connect_error', error);
socket.on('connect_timeout', error);
socket.on('error', error);
socket.on('disconnect', error);
});
};
export const newPortChecker = (url) => {
let websocket = new WebSocket(url);
// websocket.send('pinging server');
websocket.onopen = function(event) {
setInterval(() => {
websocket.send('ping');
}, 30000);
console.log(event);
};
websocket.onmessage = function(event) {
console.log(event.data);
};
websocket.onerror = function(event) {
console.log(event);
};
websocket.onclose = function(event) {
console.log(event);
};
};
export const portChecker = (cb, host, port, timeout) => {
let timeouts = (timeout == null) ? 100 : timeout;
let img = new Image();
img.onerror = function() {
if (!img) return;
img = undefined;
console.log('open');
cb('open');
};
img.onload = img.onerror;
img.src = 'https://' + host + ':' + port;
setTimeout(function() {
if (!img) return;
img = undefined;
console.log('closed');
cb('closed');
}, timeouts);
};
【问题讨论】:
标签: javascript tcp port