我通过django应用程序实现了WebSocket连接用于实时更新。问题是它在localhost中工作,但当我在公共主机服务器上托管相同的应用程序时,它无法连接。我曾经托管Daphne服务器
把我的代码放到下面
myjavascript.js
let urls=`ws://${window.location.host}/ws/socket-server/`
const Wsocket=new WebSocket(urls)
Wsocket.onmessage=function (e) {
let data=JSON.parse(e.data)
console.log(data)
}
consumer.py
# consumer.py
class SocketConsumer(WebsocketConsumer):
def connect(self):
self.accept()
self.room_group_name='test'
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.send(text_data=json.dumps({
'type':'connection_established',
'message':'you are noew connected'
}))
#routnig.py
websocket_urlpatterns=[
re_path(r'ws/socket-server',consumers.SocketConsumer.as_asgi())
]
#asgi.py
application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
'websocket':AuthMiddlewareStack(
URLRouter(
App.routing.websocket_urlpatterns
)
)
# Just HTTP for now. (We can add other protocols later.)
}
)
我利用渠道
settings.py
CHANNEL_LAYERS = {
'default': {
'BACKEND': "channels.layers.InMemoryChannelLayer"
}
}
我运行我的应用程序命令
daphne myproject.asgi:应用程序
帮帮我传奇
1条答案
按热度按时间hwamh0ep1#
您正在使用不安全的WebSocket连接-“ws://"。在您的生产服务器上,您可能正在使用安全的https连接。在安全的https连接上使用不安全的websocket(ws)是不可能的。您需要使用“wss://"来保护websocket连接。请参阅此link了解如何做到这一点。
这在本地工作,因为localhost使用http,这也是不安全的。