Skip to content

Instantly share code, notes, and snippets.

@rdeioris
Created February 7, 2020 16:38
Show Gist options
  • Save rdeioris/15cfc657351503ad0a59ccdf681410ed to your computer and use it in GitHub Desktop.
Save rdeioris/15cfc657351503ad0a59ccdf681410ed to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System;
public class MovementsServer : MonoBehaviour
{
[SerializeField]
GameObject objectToMove;
[SerializeField]
string address = "0.0.0.0";
[SerializeField]
int port = 5000;
[SerializeField]
int maxPacketsPerFrame = 100;
Socket socket;
void Awake()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Blocking = false;
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(address), port);
socket.Bind(endPoint);
Debug.Log("socket bound");
}
void Move(byte[] data, int length)
{
if (length != sizeof(float) * 3)
return;
float x = BitConverter.ToSingle(data, 0);
float y = BitConverter.ToSingle(data, 4);
float z = BitConverter.ToSingle(data, 8);
objectToMove.transform.position = new Vector3(x, y, z);
}
// Update is called once per frame
void Update()
{
byte[] data = new byte[128];
for (int i = 0; i < maxPacketsPerFrame; i++)
{
try
{
EndPoint sender = new IPEndPoint(0, 0);
int rlen = socket.ReceiveFrom(data, data.Length, SocketFlags.None, ref sender);
Debug.Log("packet received");
if (rlen > 0)
{
Debug.Log("packet received");
Move(data, rlen);
}
}
catch
{
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment