Skip to content

Instantly share code, notes, and snippets.

@HurricanKai
Created October 28, 2017 22:24
Show Gist options
  • Save HurricanKai/0c89b2b0c2dfa5e37cb398a79fe93541 to your computer and use it in GitHub Desktop.
Save HurricanKai/0c89b2b0c2dfa5e37cb398a79fe93541 to your computer and use it in GitHub Desktop.
server implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Lib
{
public class IntEventArgs : EventArgs
{
public int integer { get; set; }
public IntEventArgs(int i)
{ integer = i; }
}
public class Server
{
public event EventHandler<IntEventArgs> Receive;
public TcpListener listener;
Task listenerTask;
private bool online;
private Dictionary<TcpClient, Task> clienttasks;
public Server(int port)
{
clienttasks = new Dictionary<TcpClient, Task>();
online = true;
listener = new TcpListener(IPAddress.Any, port);
listenerTask = new Task(() =>
{
while (online)
{
if (listener.Pending())
{
var client = listener.AcceptTcpClient();
Task clienttask = new Task(() =>
{
var s = client.GetStream();
var mcs = new MinecraftStream(s);
while (client.Connected)
{
if (client.Available > 0)
{
int i = mcs.ReadInt32();
Console.WriteLine($"Got an {i}");
if (Receive != null)
Receive.Invoke(null, new IntEventArgs(i));
}
}
});
clienttasks.Add(client, clienttask);
clienttask.Start();
}
foreach (var c in clienttasks)
if (!c.Key.Connected)
clienttasks.Remove(c.Key);
}
});
listener.Start();
listenerTask.Start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment