Created
April 14, 2012 01:42
-
-
Save bschwind/2381441 to your computer and use it in GitHub Desktop.
TCP Server Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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