Skip to content

Instantly share code, notes, and snippets.

@bschwind
Created April 14, 2012 01:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bschwind/2381441 to your computer and use it in GitHub Desktop.
Save bschwind/2381441 to your computer and use it in GitHub Desktop.
TCP Server Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GraphicsToolkit.Networking;
namespace TestServer
{
public class Program
{
private static Server server;
static void Main(string[] args)
{
//Create a server which listens for clients on a given port
//Replace 16645 with the port you'd like for your server
server = new Server(16645);
server.OnDataReceived += new ServerHandlePacketData(server_OnDataReceived);
server.Start();
//Loop until the user wishes to exit
Console.WriteLine("To exit, type 'exit'");
while (true)
{
String s = Console.ReadLine();
if ("exit".Equals(s.ToLower()))
{
break;
}
//If the user types "count", print out the number of connected clients
else if ("count".Equals(s.ToLower()))
{
Console.WriteLine(server.NumClients);
}
}
Environment.Exit(0);
}
//This method is called when the server has received data from the client
static void server_OnDataReceived(byte[] data, int bytesRead, System.Net.Sockets.TcpClient client)
{
ASCIIEncoding encoder = new ASCIIEncoding();
string message = encoder.GetString(data, 0, bytesRead);
Console.WriteLine("Received a message: " + message);
server.SendImmediateToAll(encoder.GetBytes(message));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment