Skip to content

Instantly share code, notes, and snippets.

@James-Frowen
Created October 17, 2021 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save James-Frowen/1771f0b244e23633eec0102e500e08a7 to your computer and use it in GitHub Desktop.
Save James-Frowen/1771f0b244e23633eec0102e500e08a7 to your computer and use it in GitHub Desktop.
Behaviour that makes Sockets echo back message. For Mirage networking
using System.Text;
using UnityEngine;
namespace Mirage.SocketLayer
{
/// <summary>
/// Monobehaviour to help debug a cloud server, can help check if ports are open and a socket is sending message correctly
/// <para>Server will echo back the message that was sent to it</para>
/// <para>Client will send 4 byte message every second, incrementing by 1 each time</para>
/// </summary>
public class EchoSocket : MonoBehaviour
{
public SocketFactory SocketFactory;
public bool AutoStartServer;
public bool AutoStartClient;
public string Address;
private ISocket socket;
private IEndPoint endpoint;
private bool isServer;
readonly byte[] buffer = new byte[1300];
float nextPingTime;
int pingIndex;
private void Start()
{
if (AutoStartServer)
{
OpenEchoSocket();
}
else if (AutoStartClient)
{
OpenClientSocket();
}
}
public void OpenEchoSocket()
{
socket = SocketFactory.CreateServerSocket();
IEndPoint endpoint = SocketFactory.GetBindEndPoint();
socket.Bind(endpoint);
isServer = true;
}
public void OpenClientSocket()
{
socket = SocketFactory.CreateClientSocket();
endpoint = SocketFactory.GetConnectEndPoint(Address);
socket.Connect(endpoint);
isServer = false;
}
private void Update()
{
if (socket == null)
return;
while (socket.Poll())
{
int length = socket.Receive(buffer, out IEndPoint endPoint);
Debug.Log($"Packet From {endPoint}, Length:{length}, Data:[{PacketToString(buffer, length)}]");
if (isServer)
{
socket.Send(endPoint, buffer, length);
}
}
if (!isServer)
{
SendPing();
}
}
private void SendPing()
{
if (nextPingTime < UnityEngine.Time.time)
{
nextPingTime = UnityEngine.Time.time + 1;
int pos = 0;
ByteUtils.WriteUInt(buffer, ref pos, (uint)pingIndex);
pingIndex++;
socket.Send(endpoint, buffer, 4);
}
}
private string PacketToString(byte[] data, int length)
{
// log first 8 bytes
var builder = new StringBuilder();
builder.Append($"{data[0]}");
for (int i = 1; i < length || i < 8; i++)
{
builder.Append(", ");
builder.Append($"{data[1]}");
}
if (length > 8)
{
builder.Append(", ...");
}
return builder.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment