Skip to content

Instantly share code, notes, and snippets.

@GiovanniMounir
Created October 28, 2012 19:31
Show Gist options
  • Save GiovanniMounir/3969589 to your computer and use it in GitHub Desktop.
Save GiovanniMounir/3969589 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace GameServer {
class Client {
public string ID {
get;
private set;
}
public IPEndPoint EndPoint {
get;
private set;
}
Socket sck;
public Client(Socket accepted)
{
sck = accepted;
ID = Guid.NewGuid().ToString();
EndPoint = (IPEndPoint)sck.RemoteEndPoint;
sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);
}
void callback( IAsyncResult ar ) {
try {
sck.EndReceive( ar );
byte[] buf = new byte[8192];
int rec = sck.Receive( buf, buf.Length, 0 );
if( rec < buf.Length ) {
Array.Resize<byte>( ref buf, rec );
}
if( Received != null ) {
Received( this, buf );
}
sck.BeginReceive( new byte[] { 0 }, 0, 0, 0, callback, null );
} catch( Exception ex ) {
MessageBox.Show( "client - " + ex.Message );
Close();
if( Disconnected != null ) {
Disconnected( this );
}
}
}
public void Close() {
sck.Close();
}
public delegate void ClientReceivedHandler( Client sender, byte[] data );
public delegate void ClientDisconnectedHandler( Client sender );
public event ClientReceivedHandler Received;
public event ClientDisconnectedHandler Disconnected;
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
namespace GameServer {
public partial class Form1 : Form {
// ### MAIN
public bool serverRunning = false;
public int serverListenPort = 6666;
static Listener l;
public Form1() {
InitializeComponent();
l = new Listener( serverListenPort );
l.SocketAccepted += new Listener.SocketAcceptedHandler( l_SocketAccepted );
}
// Events
void l_SocketAccepted( Socket e ) {
Client client = new Client( e );
client.Received += new Client.ClientReceivedHandler( client_Received );
client.Disconnected += new Client.ClientDisconnectedHandler( client_Disconnected );
Invoke( ( MethodInvoker )delegate {
dataGridViewConnections.Rows.Add( client.ID, client.EndPoint.ToString() );
consoleWrite( DateTime.Now + " - " + client.EndPoint + " connected to server.\n\n", Color.Lime );
} );
}
void client_Received(Client sender, byte[] data)
{
if (Encoding.Default.GetString(data) != "")
{
Invoke((MethodInvoker)delegate
{
consoleWrite(DateTime.Now + "-" + sender.EndPoint + " :\n" + Encoding.Default.GetString(data) + "\n\n", Color.White); ;
});
}
}
void client_Disconnected( Client sender ) {
Invoke( ( MethodInvoker )delegate {
for( int i = 0; i < dataGridViewConnections.Rows.Count; i++ ) {
if( dataGridViewConnections.Rows[i].Cells[0].Value.ToString() == sender.ID.ToString() ) {
dataGridViewConnections.Rows.RemoveAt( i );
consoleWrite( DateTime.Now + " - " + sender.EndPoint + " disconnected from server.\n\n", Color.OrangeRed );
break;
}
}
} );
}
private void Form1_Load( object sender, EventArgs e ) {
textBoxIP.Text = getExternalIP();
}
private void checkBox1_Click(object sender, EventArgs e) {
checkBox1.Enabled = false;
if( !serverRunning ) {
consoleWrite( DateTime.Now + " " + markerSystem + "start\n", Color.White );
ServerStart();
checkBox1.Text = "Stop";
} else {
consoleWrite( DateTime.Now + " " + markerSystem + "stop\n", Color.White );
ServerStop();
checkBox1.Text = "Start";
}
checkBox1.Enabled = true;
}
// Functions
private string getExternalIP() {
System.Net.WebClient client = new System.Net.WebClient();
string ip = client.DownloadString("http://checkip.dyndns.com/");
int start = ip.IndexOf("Address: ") + 9;
int end = ip.LastIndexOf("</body>");
ip = ip.Substring( start, end - start );
return ip;
}
private void ServerStart() {
if( !serverRunning ) {
consoleWrite( "* Starting server . . .\n", Color.Orange );
// Start Server
l.Start();
serverRunning = true;
consoleWrite( "* Server started !\n", Color.Lime );
consoleWrite("Listening on port " + serverListenPort + ".\n\n", Color.White );
} else {
consoleWrite( "* ERROR: Server already started !\n\n", Color.Red );
}
}
private void ServerStop()
{
if (serverRunning)
{
consoleWrite("* Stopping server . . .\n", Color.Orange);
// Stop Server
l.Stop();
serverRunning = false;
consoleWrite("* Server stopped !\n\n", Color.Lime);
dataGridViewConnections.Rows.Clear(); // Clear connections
}
else
{
consoleWrite("* ERROR: Server already stopped !\n\n", Color.Red);
}
}
// ### CONSOLE
private string markerSystem = "@System -> ";
private string marker = "-> ";
// Events
private void consoleText_TextChanged(object sender, EventArgs e) {
consoleText.SelectionStart = consoleText.Text.Length;
consoleText.ScrollToCaret();
}
private void consoleInput_KeyPress(object sender, KeyPressEventArgs e) {
if( e.KeyChar == (char)Keys.Enter && consoleInput.Text.Trim() != "" ) {
string[] input = consoleInput.Text.Trim().ToLower().Split(' ');
consoleInput.Text = "";
string cmd = input[0];
consoleWrite( DateTime.Now + " " + marker + String.Join(" ", input) + "\n", Color.White );
// CMD - HELP
if( cmd == "help" || cmd == "?" ) {
if( input.Length == 1 ) {
consoleWrite( "---------------------------------------------\n", Color.Cyan );
consoleWrite( " help | ? - Displays this list of commands\n", Color.Cyan );
consoleWrite( " start - Starts the server\n", Color.Cyan );
consoleWrite( " stop - Stops the server\n", Color.Cyan );
consoleWrite( "---------------------------------------------\n\n", Color.Cyan );
} else {
consoleWrite( "Invalid parameter \"" + input[1] + "\"\n\n", Color.Gray );
}
// CMD - START
} else if( cmd == "start" ) {
if( input.Length == 1 ) {
ServerStart();
checkBox1.Checked = true;
checkBox1.Text = "Stop";
} else {
consoleWrite( "Invalid parameter \"" + input[1] + "\"\n\n", Color.Gray );
}
// CMD - STOP
} else if( cmd == "stop" ) {
if( input.Length == 1 ) {
ServerStop();
checkBox1.Checked = false;
checkBox1.Text = "Start";
} else {
consoleWrite( "Invalid parameter \"" + input[1] + "\"\n\n", Color.Gray );
}
// CMD - TEST
} else if( cmd == "test" ) {
int blabla;
if( input.Length == 3 ) {
if( Int32.TryParse( input[1], out blabla ) ) {
if( Int32.TryParse( input[2], out blabla ) ) {
for( int i = Int32.Parse( input[1] ); i <= Int32.Parse( input[2] ); i++ ) {
consoleWrite( i + "\n", Color.Cyan );
}
} else {
// 2 invalid
}
} else {
// par 1 invalid
}
} else {
consoleWrite( "\"" + cmd + "\" needs two parameters\n\n", Color.Gray );
}
// CMD - <INVALID>
} else {
consoleWrite( "Invalid command \"" + cmd + "\"\n\n", Color.Gray );
}
e.Handled = true;
}
}
// Functions
private void consoleWrite( string text, Color color ) {
consoleText.SelectionStart = consoleText.Text.Length;
consoleText.SelectionLength = 0;
consoleText.SelectionColor = color;
consoleText.AppendText( text );
}
}
}
namespace GameServer {
partial class Form1 {
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent() {
this.tabPages = new System.Windows.Forms.TabControl();
this.tabPageConsole = new System.Windows.Forms.TabPage();
this.consoleInput = new System.Windows.Forms.TextBox();
this.consoleText = new System.Windows.Forms.RichTextBox();
this.tabPageConnections = new System.Windows.Forms.TabPage();
this.button6 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.dataGridViewConnections = new System.Windows.Forms.DataGridView();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.textBoxIP = new System.Windows.Forms.TextBox();
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.tabPages.SuspendLayout();
this.tabPageConsole.SuspendLayout();
this.tabPageConnections.SuspendLayout();
( ( System.ComponentModel.ISupportInitialize )( this.dataGridViewConnections ) ).BeginInit();
this.SuspendLayout();
//
// tabPages
//
this.tabPages.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom )
| System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
this.tabPages.Controls.Add( this.tabPageConsole );
this.tabPages.Controls.Add( this.tabPageConnections );
this.tabPages.Location = new System.Drawing.Point( 12, 42 );
this.tabPages.Name = "tabPages";
this.tabPages.SelectedIndex = 0;
this.tabPages.Size = new System.Drawing.Size( 760, 508 );
this.tabPages.TabIndex = 3;
//
// tabPageConsole
//
this.tabPageConsole.BackColor = System.Drawing.Color.Black;
this.tabPageConsole.Controls.Add( this.consoleInput );
this.tabPageConsole.Controls.Add( this.consoleText );
this.tabPageConsole.Location = new System.Drawing.Point( 4, 22 );
this.tabPageConsole.Name = "tabPageConsole";
this.tabPageConsole.Padding = new System.Windows.Forms.Padding( 3 );
this.tabPageConsole.Size = new System.Drawing.Size( 752, 482 );
this.tabPageConsole.TabIndex = 0;
this.tabPageConsole.Text = "Console";
//
// consoleInput
//
this.consoleInput.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( ( System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
this.consoleInput.BackColor = System.Drawing.Color.Black;
this.consoleInput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.consoleInput.Font = new System.Drawing.Font( "Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ( ( byte )( 0 ) ) );
this.consoleInput.ForeColor = System.Drawing.Color.White;
this.consoleInput.Location = new System.Drawing.Point( 6, 456 );
this.consoleInput.Name = "consoleInput";
this.consoleInput.Size = new System.Drawing.Size( 740, 20 );
this.consoleInput.TabIndex = 5;
this.consoleInput.KeyPress += new System.Windows.Forms.KeyPressEventHandler( this.consoleInput_KeyPress );
//
// consoleText
//
this.consoleText.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom )
| System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
this.consoleText.AutoWordSelection = true;
this.consoleText.BackColor = System.Drawing.Color.Black;
this.consoleText.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.consoleText.Font = new System.Drawing.Font( "Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ( ( byte )( 0 ) ) );
this.consoleText.ForeColor = System.Drawing.Color.White;
this.consoleText.Location = new System.Drawing.Point( 6, 6 );
this.consoleText.Name = "consoleText";
this.consoleText.ReadOnly = true;
this.consoleText.Size = new System.Drawing.Size( 740, 444 );
this.consoleText.TabIndex = 4;
this.consoleText.Text = "";
this.consoleText.WordWrap = false;
this.consoleText.TextChanged += new System.EventHandler( this.consoleText_TextChanged );
//
// tabPageConnections
//
this.tabPageConnections.Controls.Add( this.button6 );
this.tabPageConnections.Controls.Add( this.button5 );
this.tabPageConnections.Controls.Add( this.button4 );
this.tabPageConnections.Controls.Add( this.button3 );
this.tabPageConnections.Controls.Add( this.button2 );
this.tabPageConnections.Controls.Add( this.button1 );
this.tabPageConnections.Controls.Add( this.dataGridViewConnections );
this.tabPageConnections.Location = new System.Drawing.Point( 4, 22 );
this.tabPageConnections.Name = "tabPageConnections";
this.tabPageConnections.Padding = new System.Windows.Forms.Padding( 3 );
this.tabPageConnections.Size = new System.Drawing.Size( 752, 482 );
this.tabPageConnections.TabIndex = 1;
this.tabPageConnections.Text = "Connections";
this.tabPageConnections.UseVisualStyleBackColor = true;
//
// button6
//
this.button6.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right ) ) );
this.button6.Location = new System.Drawing.Point( 596, 151 );
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size( 150, 23 );
this.button6.TabIndex = 10;
this.button6.Text = "button1";
this.button6.UseVisualStyleBackColor = true;
//
// button5
//
this.button5.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right ) ) );
this.button5.Location = new System.Drawing.Point( 596, 122 );
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size( 150, 23 );
this.button5.TabIndex = 9;
this.button5.Text = "button1";
this.button5.UseVisualStyleBackColor = true;
//
// button4
//
this.button4.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right ) ) );
this.button4.Location = new System.Drawing.Point( 596, 93 );
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size( 150, 23 );
this.button4.TabIndex = 8;
this.button4.Text = "button1";
this.button4.UseVisualStyleBackColor = true;
//
// button3
//
this.button3.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right ) ) );
this.button3.Location = new System.Drawing.Point( 596, 64 );
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size( 150, 23 );
this.button3.TabIndex = 7;
this.button3.Text = "button1";
this.button3.UseVisualStyleBackColor = true;
//
// button2
//
this.button2.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right ) ) );
this.button2.Location = new System.Drawing.Point( 596, 35 );
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size( 150, 23 );
this.button2.TabIndex = 6;
this.button2.Text = "button1";
this.button2.UseVisualStyleBackColor = true;
//
// button1
//
this.button1.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right ) ) );
this.button1.Location = new System.Drawing.Point( 596, 6 );
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size( 150, 23 );
this.button1.TabIndex = 5;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// dataGridViewConnections
//
this.dataGridViewConnections.AllowUserToAddRows = false;
this.dataGridViewConnections.AllowUserToDeleteRows = false;
this.dataGridViewConnections.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom )
| System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
this.dataGridViewConnections.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewConnections.Columns.AddRange( new System.Windows.Forms.DataGridViewColumn[] {
this.Column1,
this.Column2} );
this.dataGridViewConnections.Location = new System.Drawing.Point( 6, 6 );
this.dataGridViewConnections.Name = "dataGridViewConnections";
this.dataGridViewConnections.ReadOnly = true;
this.dataGridViewConnections.Size = new System.Drawing.Size( 584, 470 );
this.dataGridViewConnections.TabIndex = 4;
//
// checkBox1
//
this.checkBox1.Appearance = System.Windows.Forms.Appearance.Button;
this.checkBox1.Location = new System.Drawing.Point( 12, 12 );
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size( 75, 24 );
this.checkBox1.TabIndex = 0;
this.checkBox1.Text = "Start";
this.checkBox1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.checkBox1.UseVisualStyleBackColor = true;
this.checkBox1.Click += new System.EventHandler( this.checkBox1_Click );
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point( 107, 18 );
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size( 17, 13 );
this.label1.TabIndex = 4;
this.label1.Text = "IP";
//
// textBoxIP
//
this.textBoxIP.Location = new System.Drawing.Point( 130, 15 );
this.textBoxIP.Name = "textBoxIP";
this.textBoxIP.ReadOnly = true;
this.textBoxIP.Size = new System.Drawing.Size( 100, 20 );
this.textBoxIP.TabIndex = 1;
//
// Column1
//
this.Column1.HeaderText = "ID";
this.Column1.Name = "Column1";
this.Column1.ReadOnly = true;
this.Column1.Resizable = System.Windows.Forms.DataGridViewTriState.False;
//
// Column2
//
this.Column2.HeaderText = "IP";
this.Column2.Name = "Column2";
this.Column2.ReadOnly = true;
this.Column2.Resizable = System.Windows.Forms.DataGridViewTriState.False;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F );
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size( 784, 562 );
this.Controls.Add( this.textBoxIP );
this.Controls.Add( this.label1 );
this.Controls.Add( this.checkBox1 );
this.Controls.Add( this.tabPages );
this.MinimumSize = new System.Drawing.Size( 400, 300 );
this.Name = "Form1";
this.ShowIcon = false;
this.Text = "Game Server";
this.Load += new System.EventHandler( this.Form1_Load );
this.tabPages.ResumeLayout( false );
this.tabPageConsole.ResumeLayout( false );
this.tabPageConsole.PerformLayout();
this.tabPageConnections.ResumeLayout( false );
( ( System.ComponentModel.ISupportInitialize )( this.dataGridViewConnections ) ).EndInit();
this.ResumeLayout( false );
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TabControl tabPages;
private System.Windows.Forms.TabPage tabPageConsole;
private System.Windows.Forms.TabPage tabPageConnections;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.TextBox consoleInput;
private System.Windows.Forms.RichTextBox consoleText;
private System.Windows.Forms.DataGridView dataGridViewConnections;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBoxIP;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.DataGridViewTextBoxColumn Column1;
private System.Windows.Forms.DataGridViewTextBoxColumn Column2;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace GameServer
{
class Listener
{
Socket s;
public bool Listening
{
get;
private set;
}
public int Port
{
get;
private set;
}
public Listener(int port)
{
Port = port;
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Start()
{
if (Listening)
{
return;
}
// Conect
s.Bind(new IPEndPoint(0, Port));
s.Listen(0);
// End Connect
// Begin recieving packets
s.BeginAccept(callback, null);
Listening = true;
}
public void Stop()
{
if (!Listening)
{
return;
}
s.Close();
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Listening = false;
}
void callback(IAsyncResult ar)
{
try
{
Socket s = this.s.EndAccept(ar);
if (SocketAccepted != null)
{
SocketAccepted(s);
}
this.s.BeginAccept(callback, null);
}
catch (Exception ex)
{
if (!ex.Message.Contains("asyncResult"))
{
MessageBox.Show(ex.Message);
}
}
}
public delegate void SocketAcceptedHandler(Socket e);
public event SocketAcceptedHandler SocketAccepted;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace GameServer {
static class Program {
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment