LobbyServer/LobbyClientTest/FakeGameHost.cs

54 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace LobbyClientTest
{
internal class FakeGameHost
{
private Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private const int bufSize = 8 * 1024;
private State state = new State();
private EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0);
private AsyncCallback recv = null;
public bool isHost;
public class State
{
public byte[] buffer = new byte[bufSize];
}
public int Server(int port)
{
_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
_socket.ExclusiveAddressUse = false;
_socket.Bind(new IPEndPoint(IPAddress.Any, port));
Receive();
return ((IPEndPoint)_socket.LocalEndPoint!).Port;
}
public void Send(EndPoint ep, string text)
{
byte[] data = Encoding.ASCII.GetBytes(text);
_socket.SendTo(data, 0, data.Length, SocketFlags.None, ep);
}
private void Receive()
{
_socket.BeginReceiveFrom(state.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv = (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndReceiveFrom(ar, ref epFrom);
_socket.BeginReceiveFrom(so.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv, so);
Console.WriteLine($"Game {(isHost ? "host" : "client")} received: {epFrom.ToString()}: {bytes}, {Encoding.ASCII.GetString(so.buffer, 0, bytes)}");
if (isHost)
Send(epFrom, "Hello from Game Server!");
}, state);
}
}
}