I want to send data via Websocket from my django server to my unity game. The websocket connect and disconnects corectly, but i can't send any data to unity.
In django consumers.py I have this:
class SensorDataConsumer(AsyncWebsocketConsumer):
async def connect(self):
print("connected")
await self.accept()
async def disconnect(self, close_code):
print("disconnected")
pass
async def receive(self, text_data):
# Process the received message from Unity if needed
print("received")
pass
async def send_data(self, event):
message = event['message']
print("Sending data:", message)
await self.send(text_data=message)
In routing.py I have this:
websocket_urlpatterns = [
re_path(r'ws/sensordata/$', SensorDataConsumer.as_asgi()),
]
I set the asgi like this:
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": URLRouter(websocket_urlpatterns)
})
When the game starts, i connect the websocket. When the method send_sensor_data from views.py is called, i want to send the data to unity. I have this code for the method:
@api_view(['POST'])
def send_sensor_data(request):
sensor_data_consumer = SensorDataConsumer()
async_to_sync(sensor_data_consumer.send_data({'message': 'Hello, world!'}))
return Response({'success': True})
In Unity, I have a script for websocket:
public class SensorDataReceiver : MonoBehaviour
{
private WebSocket ws;
void Start()
{
ws = new WebSocket("ws://192.168.1.5:8000/ws/sensordata/");
ws.OnMessage += OnMessageReceived;
ws.Connect();
}
void OnMessageReceived(object sender, MessageEventArgs e)
{
// Handle the received message here
Debug.Log("Received message: " + e.Data);
}
void OnDestroy()
{
if (ws != null)
{
ws.OnMessage -= OnMessageReceived;
ws.Close();
ws = null;
}
}
}
I tried a lot of ways to send the data but it does not send anything, only connection and disconnection work.