这是我的客户端(unity3d C#代码),我正在连接python websocket服务器
private WebSocket ws;
public bool isAlive;
void Start()
{
ws = new WebSocket("ws://127.0.0.1:3000");//127.0.0.1
ws.OnClose += (sender, e) =>
{
Debug.Log("Opened");
};
ws.OnMessage += (sender, e) =>
{
Debug.Log("WebSocket Message Type :" + e.Type + ", Data: " + e.Data);
};
ws.OnClose += (sender, e) =>
{
Debug.Log("Close");
};
ws.OnError += (sender, e) =>
{
//Debug.Log("error Sender : " + sender.ToString());
Debug.Log("error Message :" + e.Message);
};
ws.Connect();
}
我有这个代码连接网络套接字但是当我的场景启动时它会触发错误事件,我得到了这个
错误消息:连接时发生错误。 UnityEngine.Debug:Log(Object)NodeWebSocketCaller:m__3(Object, ErrorEventArgs)(在Assets / NodeWebSocketCaller.cs:30) WebSocketSharp.Ext:Emit(EventHandler`1,Object,ErrorEventArgs)(at 资产/ SocketIO / WebsocketSharp / Ext.cs:992) WebSocketSharp.WebSocket:error(String)(at 资产/ SocketIO / WebsocketSharp / WebSocket.cs:1011) WebSocketSharp.WebSocket:doHandshake()(at 资产/ SocketIO / WebsocketSharp / WebSocket.cs:989) WebSocketSharp.WebSocket:connect()(at 资产/ SocketIO / WebsocketSharp / WebSocket.cs:874) WebSocketSharp.WebSocket:Connect()(at 资产/ SocketIO / WebsocketSharp / WebSocket.cs:1784) NodeWebSocketCaller:Start()(在Assets / NodeWebSocketCaller.cs:32)
开启和关闭事件也在执行。
在服务器端:
import cherrypy
from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from ws4py.websocket import WebSocket
class Root(object):
@cherrypy.expose
def index(self):
return 'some html with a webcsocekt js connectino'
@cherrypy.expose
def ws(self):
#you can access the class instance through
handler = cherrypy.request.ws_handler
class AgentServer(WebSocket):
def openend(self):
print("Opened!")
def closed(self, code, reason):
print("Closed")
def received_message(self, m):
self.send(m.data, m.is_binary)
if __name__ == "__main__":
cherrypy.config.update({
"server.socket_host": "127.0.0.1",
"server.socket_port": 3000,
})
WebSocketPlugin(cherrypy.engine).subscribe()
cherrypy.tools.websocket = WebSocketTool()
cherrypy.quickstart(Root(), "/", config ={
"/ws": {
"tools.websocket.on":True,
"tools.websocket.handler_cls": AgentServer,
}
})
请不要问关于python代码的问题我不熟悉它。我刚从互联网上获取此代码。