jinbeizame007 score 8
2016/05/29 22:01 投稿
WebSocketを利用したUnityとPythonの接続について |
###前提・実現したいこと |
UnityとPythonとWebSocketを使い、Pythonでサーバを用意し、Unityが文字列を送るとPythonが同じ文字列を返すシステムを作っています。Pythonはws4py、UnityはWebSocketSharpを使用しています。 |
###発生している問題・エラーメッセージ |
現在、UnityとPythonの接続すら出来ていない状態です。 |
接続しようとしてUnity側でOpenせずCloseだけします。 |
###該当のソースコード |
Unity |
```ここに言語を入力 |
using UnityEngine; |
using System.Collections; |
using WebSocketSharp; |
using WebSocketSharp.Net; |
public class Net : MonoBehaviour { |
public string WSAddress = "ws://127.0.0.1:3000"; |
WebSocket ws; |
void Start(){ |
Connect(); |
} |
void Connect () { |
ws = new WebSocket (WSAddress); |
ws.OnOpen += (sender, e) => { |
Debug.Log ("WebSocket Open"); |
}; |
ws.OnMessage += (sender, e) => { |
Debug.Log ("WebSocket Message Type: " + e.Type + ", Data: " + e.Data); |
}; |
ws.OnError += (sender, e) => { |
Debug.Log ("WebSocket Error Message: " + e.Message); |
}; |
ws.OnClose += (sender, e) => { |
Debug.Log ("WebSocket Close"); |
}; |
ws.Connect (); |
} |
void Send (string message) { |
ws.Send (message); |
} |
void FixedUpdate(){ |
if (Input.GetKeyUp (KeyCode.Space)) { |
Send ("Test Message"); |
} |
} |
} |
``` |
Python3 |
``` |
import cherrypy |
from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool |
from ws4py.websocket import WebSocket |
cherrypy.config.update({'server.socket_port': 3000}) |
WebSocketPlugin(cherrypy.engine).subscribe() |
cherrypy.tools.websocket = WebSocketTool() |
class Root(object): |
@cherrypy.expose |
def index(self): |
return 'some HTML with a websocket javascript connection' |
@cherrypy.expose |
def ws(self): |
# you can access the class instance through |
return 'received' |
handler = cherrypy.request.ws_handler |
class AgentServer(WebSocket): |
def opened(self): |
print ("Socket opened") |
def received_message(self, m): |
self.send('received') |
cherrypy.quickstart(Root(), '/', config={'/ws': {'tools.websocket.on': True, |
'tools.websocket.handler_cls': WebSocket}}) |
``` |
###エラーメッセージ |
An error has occurred in sending data. |
###補足情報(言語/FW/ツール等のバージョンなど) |
Unity5,Python3.5.1 |
初学者でしてまだWebSocketなどの理解もあまり出来ていない状態です。丁寧に教えて頂けるととても嬉しいです。 |