【发布时间】:2025-12-01 17:20:06
【问题描述】:
我在使用 websocket 连接的地方运行我的程序。以前,我的程序运行正确,但今天我收到错误消息 websocket 连接未干净关闭,需要升级 426。在客户端我使用高速公路扭曲版本 15.4.0,在服务器中我在节点 js 中使用 ws websocket。 请给我一些建议。 谢谢。
这是我的客户端代码:
##WebSocket Class
class MyClientProtocol (WebSocketClientProtocol):
def onConnect(self, response):
status = "Server connected: {0}".format(response.peer)
logData(status)
def onOpen(self):
status ="WebSocket connection open."
logData (status)
def SentData ():
select()
if (numberOfData==0): #jika data kosong koneksi terputus
# if there is no data, connection will closed
self.sendClose()
else:
self.sendMessage (dataSent.encode('utf8')) #send data if file not empty
SentData ()
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
# if server sent ack connection will close
if (payload.decode('utf8')=="ok"):
print("Text message received")
status="data sent"
logData(status)
dataNew[:]=[]
update()
# get time while sent
#p=subprocess.Popen("date", stdout=subprocess.PIPE, shell=True)
#output= str(p.communicate())
#logData(output)
self.sendClose ()
else:
# if server sent nack, data will resend
self.sendMessage(dataSent.encode('utf8'))
def onClose(self, wasClean, code, reason):
status ="WebSocket connection closed code [{}]: {}".format(code,reason)
logData (status)
self.factory.reactor.callLater (int(interval),webSocketConnect)#send data every 10 seconds
#websocket connection function
def webSocketConnect ():
factory = WebSocketClientFactory (u"wss://node-imamabdul-2.c9.io:8080", debug=False)
factory.protocol = MyClientProtocol
reactor.connectTCP("node-imamabdul-2.c9.io",8080, factory)
#SIGINT
def SIGINT_CustomEventHandler(num, frame):
k={1:"SIGHUP", 2:"SIGINT"}
status="Recieved signal - " + k[num]
logData(status)
if frame is not None:
status="SIGINT at %s:%s"%(frame.f_code.co_name, frame.f_lineno)
logData(status)
status="In SIGINT Custom Handler Shutting Down ..."
logData (status)
if num == 2:
#status= "shutting down ...."
exitFlag=True
reactor.stop()
## main
if __name__ == '__main__':
readID()
conn = sqlite3.connect(vcspath+'vcsdb2.db')
cur= conn.cursor()
create ()
## global variables
#os.system("hwclock -w -f /dev/rtc1")
exitFlag = False
Data =[]
DataStatus=False
#makeDir ()
webSocketConnect()
signal.signal(signal.SIGINT, SIGINT_CustomEventHandler)
reactor.run()
这是我的服务器代码:
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ port: process.env.PORT });
port = process.env.PORT;
console.log("PORT :" + port);
wss.on('connection', function connection(wss) {
console.log("connection opened" + wss.listeners());
wss.on('message', function incoming(message) {
console.log("connection has message: " + message)
var fs = require('fs');
var timestamp = new Date().toString('hex')
fs.appendFile('fromclient.csv',"['"+timestamp+"']"+' ' + message+'\n')
wss.send(message);
});
wss.on('close', function closeSocket() {
console.log("connection closed");
});
wss.on('error', function socketError() {
console.log("connection has error");
});
});
【问题讨论】:
-
尝试使用浏览器中的 javascript 连接到您的服务器...可以连接还是出现错误? (尝试隔离问题 - 是服务器问题还是客户端问题)?
-
我可以连接到我的服务器。如果我连接 atubahn twisted v11,它也可以连接。
-
对不起,伊玛目,我没听懂您的回答...当您尝试连接高速公路 v11 时,您可以连接(工作)吗?使用 javascript 中的原始 websockets(没有库)你无法连接(不工作)?当您尝试使用高速公路 v15 时,您无法连接(不工作)?
-
你能发布一些代码吗?编辑您的问题并添加用于连接到服务器的代码。
-
对不起,我刚刚看到您在评论中更新了答案...从您的回答中我知道这是客户问题...