UDP
UDP does not work on a web build To work in editor in Windows, open Defender and sort by name to check all unity configs.
Use this to share data in a local network. You can find local clients with broadcast and retrieves the local address to start a server, share data between a pc and a smartphone connected on the same wifi...
This is more simple than Tcp connection: no networks, no dialogs, no responses.
For simple address sharing and nearby player, see Simple LocalNetwork
Simple UDP
Provides a very simple API to use UDP (but it is not a real connection).
// listen buffer or string
var mylistener = SimpleUdp.Listen(9580 /* port */, (byte[] buffer, IPEndPoint remote) => { }, /* IPAddress = Any */);
var mylistener = SimpleUdp.ListenString(9580 /* port */, (string msg, IPEndPoint remote) => { }, /* IPAddress = Any */);
// send data
await SimpleUdp.Send(stringOrBytes, "localhost", 9581 /* port */);
Server
UdpServer _server;
void Start() {
_server = new UdpServer("unique key", /* broadcastPort = 9565, msgPort = 9566, timeout = 2f */);
_server.OnConnected += OnPeerConnected;
_server.OnDisconnected += OnPeerDisconnected;
_server.Start();
}
void OnPeerConnected(UdpPeer peer) {
Debug.Log("New connection " + peer.EndPoint.Address.ToString());
peer.AddHandler(1, packet => {
var pos = packet.Read<Vector3>();
transform.localPosition = pos + new Vector3(1f, 0f, 0f);
peer.Send(4, "Your Address is "+peer.EndPoint.Address);
});
}
Client
UdpClient _client;
void Start() {
_client = new UdpClient("unique key", /* broadcastPort = 9565, msgPort = 9566, timeout = 2f */);
_client.OnConnected += () => Debug.Log("Connected to server : " + _client.ServerAddress);
client.AddHandler(4 /* message ID */, packet => {
Debug.LogError("Message from server: "+packet.Read<string>());
});
_client.Start();
StartCoroutine(UpdatePositionRoutine());
}
IEnumerator UpdatePositionRoutine() {
while (!_client.IsConnected) {
yield return new WaitForSeconds(0.4f);
}
while (_client.IsConnected) {
_client.Send(1 /* message ID */, transform.localPosition);
yield return new WaitForSeconds(0.1f);
}
}