我知道如何在本地機器上建立服務器和客戶端之間的websocket握手。但我不知道,我應該在哪裏挖掘才能從碼頭集裝箱執行此操作。我總是net::ERR_CONNECTION_REFUSED
Docker中的Tornado websocket(net :: ERR_CONNECTION_REFUSED)
這裏是我的客戶端client.html
:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
ws = new WebSocket("ws://localhost:8888/ws");
ws.onmessage = function(evt) {
console.log("Message Received: " + evt.data)
}
ws.onopen = function(evt) {
console.log("***Connection Opened***");
}
ws.onclose = function(evt) {
console.log("***Connection Closed***");
}
</script>
</head>
</html>
這裏是我的簡單的龍捲風的WebSocket的解決方案server.py
:
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import socket
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print ('new connection')
if self not in wss:
wss.append(self)
def on_message(self, message):
print ('message received: %s' % message)
# Reverse Message and send it back
print ('sending back message: %s' % message[::-1])
self.write_message(message[::-1])
def on_close(self):
print ('connection closed')
if self in wss:
wss.remove(self)
def check_origin(self, origin):
return True
application = tornado.web.Application([
(r'/ws', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
myIP = socket.gethostbyname(socket.gethostname())
print ('*** Websocket Server Started at %s***' % myIP)
main_loop = tornado.ioloop.IOLoop.instance()
main_loop.start()
我跑python3 server.py
。收到*** Websocket Server Started at 5.255.232.98***
。然後,當我在瀏覽器(只是一個文件)中打開client.html,並在控制檯ws.send('hooray')
中打印時,我收到了反轉變體Message Received: yarooh
。一切都好。
然後我嘗試從docker啓動我的server.py
。 我跑碼頭工人容器:
docker run -ti -d -p 80:80 -v <path to server.py folder>:/root --name <my_name> <my_container>
然後運行python3 server.py
。收到:*** Websocket Server Started at 172.17.0.2***
。 那麼,當我再次打開client.html
,我收到以下錯誤:
client.html:7 WebSocket connection to 'ws://localhost:8888/ws' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
我想問題應該是我docker run -p 80:80
的選擇,但我不知道如何解決它。我需要docker run -p 80:80
,因爲我也有django服務器(我沒有在實驗期間運行nginx和Django)。