I’m trying to figure out how to connect two clients through the server, in my racing game the car will be controlled using an external controller that will be connected to the server as a client, it will send requests to the server, and the server will redirect them to the client application, but I can’t figure out how to connect it. I am using WebSocketSharp c# as clients and server python websockets library.
Client1, Client2:
using System;
using UnityEngine;
using WebSocketSharp;
public class Client1 : MonoBehaviour
{
WebSocket ws;
public GameObject target;
private Vector3 targetPoint;
private Quaternion targetRotation;
private void Start()
{
ws = new WebSocket("ws://127.0.0.1:8080");
ws.Connect();
ws.OnMessage += (sender, e) =>
{
Debug.Log("Message recived from " + ((WebSocket)sender).Url + ", Data: " + e.Data);
};
}
void Update()
{
if (ws == null)
return;
if (Input.GetKeyDown(KeyCode.Z))
ws.Send("I Client1!");
// как принять сообщение от сервера??????
// targetPoint = new Vector3(target.transform.position.x, transform.position.y, target.transform.position.z) - transform.position;
// targetRotation = Quaternion.LookRotation(targetPoint, Vector3.up);
// transform.rotation = targetRotation;
}
}
using System;
using UnityEngine;
using WebSocketSharp;
public class Client2 : MonoBehaviour
{
WebSocket ws;
public GameObject target;
private Vector3 targetPoint;
private Quaternion targetRotation;
private void Start()
{
ws = new WebSocket("ws://127.0.0.1:8080");
ws.Connect();
ws.OnMessage += (sender, e) =>
{
Debug.Log("Message recived from " + ((WebSocket)sender).Url + ", Data: " + e.Data);
};
}
void Update()
{
if (ws == null)
return;
if (Input.GetKeyDown(KeyCode.X))
ws.Send("I Client2!");
// как принять сообщение от сервера??????
// targetPoint = new Vector3(target.transform.position.x, transform.position.y, target.transform.position.z) - transform.position;
// targetRotation = Quaternion.LookRotation(targetPoint, Vector3.up);
// transform.rotation = targetRotation;
}
}
Server:
import websockets
import asyncio
PORT = 8080
connected = set()
print("Server listening on Port "+ str(PORT))
async def echo(websocket, path):
print("A client just connected")
connected.add(websocket)
try:
async for message in websocket:
# print("Received message from client: " + message)
for conn in connected:
if conn != websocket:
await conn.send(message)
except websockets.exceptions.ConnectionClosed:
print("A client just disconnected")
start_server = websockets.serve(echo, "localhost", PORT)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()