【问题标题】:Websocket Upgrade Required 426需要 Websocket 升级 426
【发布时间】: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 时,您无法连接(不工作)?
  • 你能发布一些代码吗?编辑您的问题并添加用于连接到服务器的代码。
  • 对不起,我刚刚看到您在评论中更新了答案...从您的回答中我知道这是客户问题...

标签: python node.js websocket


【解决方案1】:

在您的代码中,您使用的是加密的 websockets 连接,此处(在您的 python 代码中):

#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)

因为您正在使用带有 wss 的 Autobahn 15.4.0,所以您正在体验 the issue (bug) that exists in Autobahn version 15.4.0

问题已在 9 天前修复。

您需要将 Autobahn 更新到修复后的版本(真正的新版本,如果它已发布)或将 Autobahn 降级到问题(错误)出现之前的版本。

另一种选择是使用ws 而不是wss - 这意味着您的连接不会被加密,因此不推荐这样做。

祝你好运!

【讨论】:

  • 我想我的问题是在我尝试连接 GSM 调制解调器时出现的。但是,当我使用 LAN 连接时,我没有遇到这个问题。
  • 感谢您的建议。如何升级/降级我的高速公路?但是当我使用 LAN/eth0 连接时,我没有收到该错误消息。
  • 我认为您没有为本地服务器设置 SSL...所以当您连接到本地服务器时,您使用 ws 而不是 wss... 或者也许高速公路的错误这样有趣......至于升级,我不知道。您是如何安装 15.4.0 版的?我看到的是 0.10.9 版本……也许在正式发布之前继续使用旧版本?