Simple TCP/IP Server Code

From Unify Community Wiki
Revision as of 20:47, 10 January 2012 by NCarter (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Here is the C# code for the server binary. Create a new Windows Forms application and add this code to the project. The frmMain is the main form for the application. This code is a modified version of the 101 C# example for the advanced TCP/IP server piece from MSDN. (Freely available)

frmMain.cs code:

// Initial tcp/ip server component taken from MSDN 101 examples, advanced networking in C#
// Modified to display a little more information and to ignore invalid packets
// Most of the server piece is still intact for simple chat
// This is for Proof of Concept ONLY 
// This is to show how to make a simple game server
// At this point, all messages received come across with a CHAT and is parsed
 
using System;
using System.Collections;
using System.Threading;
using System.Windows.Forms;
using System.Net.Sockets;
 
public class frmMain : System.Windows.Forms.Form 
{
 
#region " Windows Form Designer generated code "
 
	/// <summary>
	/// The main entry point for the application.
	/// </summary>
	[STAThread]
	static void Main() 
	{
		Application.Run(new frmMain());
	}
 
    public frmMain() 
	{
        //This call is required by the Windows Form Designer.
        InitializeComponent();
        //Add any initialization after the InitializeComponent() call
        // So that we only need to set the title of the application once,
        // we use the AssemblyInfo class (defined in the AssemblyInfo.cs file)
        // to read the AssemblyTitle attribute.
        AssemblyInfo ainfo = new AssemblyInfo();
        this.Text = ainfo.Title;
        this.mnuAbout.Text = string.Format("&About {0} ...", ainfo.Title);
    }
 
    //Form overrides dispose to clean up the component list.
    protected override void Dispose(bool disposing) {
        if (disposing) {
            if (components != null) {
                components.Dispose();
            }
        }
        base.Dispose(disposing);
    }
    //Required by the Windows Form Designer
    private System.ComponentModel.IContainer components = null;
    //NOTE: The following procedure is required by the Windows Form Designer
    //It can be modified using the Windows Form Designer.  
    //Do not modify it using the code editor.
    private System.Windows.Forms.MainMenu mnuMain;
 
    private System.Windows.Forms.MenuItem mnuFile;
 
    private System.Windows.Forms.MenuItem mnuExit;
 
    private System.Windows.Forms.MenuItem mnuHelp;
 
    private System.Windows.Forms.MenuItem mnuAbout;
 
    private System.Windows.Forms.ListBox lstStatus;
 
    private System.Windows.Forms.Button btnBroadcast;
 
    private System.Windows.Forms.TextBox txtBroadcast;
 
    private System.Windows.Forms.Label lblInstructions;
	private System.Windows.Forms.ListBox lstPlayers;
	private System.Windows.Forms.Label label2;
	private System.Windows.Forms.Button btnPM;
	private System.Windows.Forms.Button btnKick;
	private System.Windows.Forms.TextBox textBox1;
	private System.Windows.Forms.Label label3;
 
    private System.Windows.Forms.Label Label1;
 
    private void InitializeComponent() {
		System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmMain));
		this.mnuMain = new System.Windows.Forms.MainMenu();
		this.mnuFile = new System.Windows.Forms.MenuItem();
		this.mnuExit = new System.Windows.Forms.MenuItem();
		this.mnuHelp = new System.Windows.Forms.MenuItem();
		this.mnuAbout = new System.Windows.Forms.MenuItem();
		this.lstStatus = new System.Windows.Forms.ListBox();
		this.txtBroadcast = new System.Windows.Forms.TextBox();
		this.btnBroadcast = new System.Windows.Forms.Button();
		this.lblInstructions = new System.Windows.Forms.Label();
		this.Label1 = new System.Windows.Forms.Label();
		this.lstPlayers = new System.Windows.Forms.ListBox();
		this.label2 = new System.Windows.Forms.Label();
		this.btnPM = new System.Windows.Forms.Button();
		this.btnKick = new System.Windows.Forms.Button();
		this.textBox1 = new System.Windows.Forms.TextBox();
		this.label3 = new System.Windows.Forms.Label();
		this.SuspendLayout();
		// 
		// mnuMain
		// 
		this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																				this.mnuFile,
																				this.mnuHelp});
		this.mnuMain.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("mnuMain.RightToLeft")));
		// 
		// mnuFile
		// 
		this.mnuFile.Enabled = ((bool)(resources.GetObject("mnuFile.Enabled")));
		this.mnuFile.Index = 0;
		this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																				this.mnuExit});
		this.mnuFile.Shortcut = ((System.Windows.Forms.Shortcut)(resources.GetObject("mnuFile.Shortcut")));
		this.mnuFile.ShowShortcut = ((bool)(resources.GetObject("mnuFile.ShowShortcut")));
		this.mnuFile.Text = resources.GetString("mnuFile.Text");
		this.mnuFile.Visible = ((bool)(resources.GetObject("mnuFile.Visible")));
		// 
		// mnuExit
		// 
		this.mnuExit.Enabled = ((bool)(resources.GetObject("mnuExit.Enabled")));
		this.mnuExit.Index = 0;
		this.mnuExit.Shortcut = ((System.Windows.Forms.Shortcut)(resources.GetObject("mnuExit.Shortcut")));
		this.mnuExit.ShowShortcut = ((bool)(resources.GetObject("mnuExit.ShowShortcut")));
		this.mnuExit.Text = resources.GetString("mnuExit.Text");
		this.mnuExit.Visible = ((bool)(resources.GetObject("mnuExit.Visible")));
		this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click);
		// 
		// mnuHelp
		// 
		this.mnuHelp.Enabled = ((bool)(resources.GetObject("mnuHelp.Enabled")));
		this.mnuHelp.Index = 1;
		this.mnuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																				this.mnuAbout});
		this.mnuHelp.Shortcut = ((System.Windows.Forms.Shortcut)(resources.GetObject("mnuHelp.Shortcut")));
		this.mnuHelp.ShowShortcut = ((bool)(resources.GetObject("mnuHelp.ShowShortcut")));
		this.mnuHelp.Text = resources.GetString("mnuHelp.Text");
		this.mnuHelp.Visible = ((bool)(resources.GetObject("mnuHelp.Visible")));
		// 
		// mnuAbout
		// 
		this.mnuAbout.Enabled = ((bool)(resources.GetObject("mnuAbout.Enabled")));
		this.mnuAbout.Index = 0;
		this.mnuAbout.Shortcut = ((System.Windows.Forms.Shortcut)(resources.GetObject("mnuAbout.Shortcut")));
		this.mnuAbout.ShowShortcut = ((bool)(resources.GetObject("mnuAbout.ShowShortcut")));
		this.mnuAbout.Text = resources.GetString("mnuAbout.Text");
		this.mnuAbout.Visible = ((bool)(resources.GetObject("mnuAbout.Visible")));
		this.mnuAbout.Click += new System.EventHandler(this.mnuAbout_Click);
		// 
		// lstStatus
		// 
		this.lstStatus.AccessibleDescription = resources.GetString("lstStatus.AccessibleDescription");
		this.lstStatus.AccessibleName = resources.GetString("lstStatus.AccessibleName");
		this.lstStatus.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lstStatus.Anchor")));
		this.lstStatus.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("lstStatus.BackgroundImage")));
		this.lstStatus.ColumnWidth = ((int)(resources.GetObject("lstStatus.ColumnWidth")));
		this.lstStatus.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lstStatus.Dock")));
		this.lstStatus.Enabled = ((bool)(resources.GetObject("lstStatus.Enabled")));
		this.lstStatus.Font = ((System.Drawing.Font)(resources.GetObject("lstStatus.Font")));
		this.lstStatus.HorizontalExtent = ((int)(resources.GetObject("lstStatus.HorizontalExtent")));
		this.lstStatus.HorizontalScrollbar = ((bool)(resources.GetObject("lstStatus.HorizontalScrollbar")));
		this.lstStatus.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lstStatus.ImeMode")));
		this.lstStatus.IntegralHeight = ((bool)(resources.GetObject("lstStatus.IntegralHeight")));
		this.lstStatus.ItemHeight = ((int)(resources.GetObject("lstStatus.ItemHeight")));
		this.lstStatus.Location = ((System.Drawing.Point)(resources.GetObject("lstStatus.Location")));
		this.lstStatus.Name = "lstStatus";
		this.lstStatus.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lstStatus.RightToLeft")));
		this.lstStatus.ScrollAlwaysVisible = ((bool)(resources.GetObject("lstStatus.ScrollAlwaysVisible")));
		this.lstStatus.Size = ((System.Drawing.Size)(resources.GetObject("lstStatus.Size")));
		this.lstStatus.TabIndex = ((int)(resources.GetObject("lstStatus.TabIndex")));
		this.lstStatus.Visible = ((bool)(resources.GetObject("lstStatus.Visible")));
		// 
		// txtBroadcast
		// 
		this.txtBroadcast.AccessibleDescription = resources.GetString("txtBroadcast.AccessibleDescription");
		this.txtBroadcast.AccessibleName = resources.GetString("txtBroadcast.AccessibleName");
		this.txtBroadcast.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtBroadcast.Anchor")));
		this.txtBroadcast.AutoSize = ((bool)(resources.GetObject("txtBroadcast.AutoSize")));
		this.txtBroadcast.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtBroadcast.BackgroundImage")));
		this.txtBroadcast.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtBroadcast.Dock")));
		this.txtBroadcast.Enabled = ((bool)(resources.GetObject("txtBroadcast.Enabled")));
		this.txtBroadcast.Font = ((System.Drawing.Font)(resources.GetObject("txtBroadcast.Font")));
		this.txtBroadcast.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtBroadcast.ImeMode")));
		this.txtBroadcast.Location = ((System.Drawing.Point)(resources.GetObject("txtBroadcast.Location")));
		this.txtBroadcast.MaxLength = ((int)(resources.GetObject("txtBroadcast.MaxLength")));
		this.txtBroadcast.Multiline = ((bool)(resources.GetObject("txtBroadcast.Multiline")));
		this.txtBroadcast.Name = "txtBroadcast";
		this.txtBroadcast.PasswordChar = ((char)(resources.GetObject("txtBroadcast.PasswordChar")));
		this.txtBroadcast.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtBroadcast.RightToLeft")));
		this.txtBroadcast.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtBroadcast.ScrollBars")));
		this.txtBroadcast.Size = ((System.Drawing.Size)(resources.GetObject("txtBroadcast.Size")));
		this.txtBroadcast.TabIndex = ((int)(resources.GetObject("txtBroadcast.TabIndex")));
		this.txtBroadcast.Text = resources.GetString("txtBroadcast.Text");
		this.txtBroadcast.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtBroadcast.TextAlign")));
		this.txtBroadcast.Visible = ((bool)(resources.GetObject("txtBroadcast.Visible")));
		this.txtBroadcast.WordWrap = ((bool)(resources.GetObject("txtBroadcast.WordWrap")));
		// 
		// btnBroadcast
		// 
		this.btnBroadcast.AccessibleDescription = resources.GetString("btnBroadcast.AccessibleDescription");
		this.btnBroadcast.AccessibleName = resources.GetString("btnBroadcast.AccessibleName");
		this.btnBroadcast.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnBroadcast.Anchor")));
		this.btnBroadcast.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnBroadcast.BackgroundImage")));
		this.btnBroadcast.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnBroadcast.Dock")));
		this.btnBroadcast.Enabled = ((bool)(resources.GetObject("btnBroadcast.Enabled")));
		this.btnBroadcast.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnBroadcast.FlatStyle")));
		this.btnBroadcast.Font = ((System.Drawing.Font)(resources.GetObject("btnBroadcast.Font")));
		this.btnBroadcast.Image = ((System.Drawing.Image)(resources.GetObject("btnBroadcast.Image")));
		this.btnBroadcast.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnBroadcast.ImageAlign")));
		this.btnBroadcast.ImageIndex = ((int)(resources.GetObject("btnBroadcast.ImageIndex")));
		this.btnBroadcast.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnBroadcast.ImeMode")));
		this.btnBroadcast.Location = ((System.Drawing.Point)(resources.GetObject("btnBroadcast.Location")));
		this.btnBroadcast.Name = "btnBroadcast";
		this.btnBroadcast.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnBroadcast.RightToLeft")));
		this.btnBroadcast.Size = ((System.Drawing.Size)(resources.GetObject("btnBroadcast.Size")));
		this.btnBroadcast.TabIndex = ((int)(resources.GetObject("btnBroadcast.TabIndex")));
		this.btnBroadcast.Text = resources.GetString("btnBroadcast.Text");
		this.btnBroadcast.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnBroadcast.TextAlign")));
		this.btnBroadcast.Visible = ((bool)(resources.GetObject("btnBroadcast.Visible")));
		this.btnBroadcast.Click += new System.EventHandler(this.btnBroadcast_Click);
		// 
		// lblInstructions
		// 
		this.lblInstructions.AccessibleDescription = resources.GetString("lblInstructions.AccessibleDescription");
		this.lblInstructions.AccessibleName = resources.GetString("lblInstructions.AccessibleName");
		this.lblInstructions.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblInstructions.Anchor")));
		this.lblInstructions.AutoSize = ((bool)(resources.GetObject("lblInstructions.AutoSize")));
		this.lblInstructions.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblInstructions.Dock")));
		this.lblInstructions.Enabled = ((bool)(resources.GetObject("lblInstructions.Enabled")));
		this.lblInstructions.Font = ((System.Drawing.Font)(resources.GetObject("lblInstructions.Font")));
		this.lblInstructions.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(0)), ((System.Byte)(192)));
		this.lblInstructions.Image = ((System.Drawing.Image)(resources.GetObject("lblInstructions.Image")));
		this.lblInstructions.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblInstructions.ImageAlign")));
		this.lblInstructions.ImageIndex = ((int)(resources.GetObject("lblInstructions.ImageIndex")));
		this.lblInstructions.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblInstructions.ImeMode")));
		this.lblInstructions.Location = ((System.Drawing.Point)(resources.GetObject("lblInstructions.Location")));
		this.lblInstructions.Name = "lblInstructions";
		this.lblInstructions.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblInstructions.RightToLeft")));
		this.lblInstructions.Size = ((System.Drawing.Size)(resources.GetObject("lblInstructions.Size")));
		this.lblInstructions.TabIndex = ((int)(resources.GetObject("lblInstructions.TabIndex")));
		this.lblInstructions.Text = resources.GetString("lblInstructions.Text");
		this.lblInstructions.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblInstructions.TextAlign")));
		this.lblInstructions.Visible = ((bool)(resources.GetObject("lblInstructions.Visible")));
		// 
		// Label1
		// 
		this.Label1.AccessibleDescription = resources.GetString("Label1.AccessibleDescription");
		this.Label1.AccessibleName = resources.GetString("Label1.AccessibleName");
		this.Label1.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("Label1.Anchor")));
		this.Label1.AutoSize = ((bool)(resources.GetObject("Label1.AutoSize")));
		this.Label1.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("Label1.Dock")));
		this.Label1.Enabled = ((bool)(resources.GetObject("Label1.Enabled")));
		this.Label1.Font = ((System.Drawing.Font)(resources.GetObject("Label1.Font")));
		this.Label1.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(0)), ((System.Byte)(192)));
		this.Label1.Image = ((System.Drawing.Image)(resources.GetObject("Label1.Image")));
		this.Label1.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("Label1.ImageAlign")));
		this.Label1.ImageIndex = ((int)(resources.GetObject("Label1.ImageIndex")));
		this.Label1.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("Label1.ImeMode")));
		this.Label1.Location = ((System.Drawing.Point)(resources.GetObject("Label1.Location")));
		this.Label1.Name = "Label1";
		this.Label1.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("Label1.RightToLeft")));
		this.Label1.Size = ((System.Drawing.Size)(resources.GetObject("Label1.Size")));
		this.Label1.TabIndex = ((int)(resources.GetObject("Label1.TabIndex")));
		this.Label1.Text = resources.GetString("Label1.Text");
		this.Label1.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("Label1.TextAlign")));
		this.Label1.Visible = ((bool)(resources.GetObject("Label1.Visible")));
		// 
		// lstPlayers
		// 
		this.lstPlayers.AccessibleDescription = resources.GetString("lstPlayers.AccessibleDescription");
		this.lstPlayers.AccessibleName = resources.GetString("lstPlayers.AccessibleName");
		this.lstPlayers.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lstPlayers.Anchor")));
		this.lstPlayers.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("lstPlayers.BackgroundImage")));
		this.lstPlayers.ColumnWidth = ((int)(resources.GetObject("lstPlayers.ColumnWidth")));
		this.lstPlayers.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lstPlayers.Dock")));
		this.lstPlayers.Enabled = ((bool)(resources.GetObject("lstPlayers.Enabled")));
		this.lstPlayers.Font = ((System.Drawing.Font)(resources.GetObject("lstPlayers.Font")));
		this.lstPlayers.HorizontalExtent = ((int)(resources.GetObject("lstPlayers.HorizontalExtent")));
		this.lstPlayers.HorizontalScrollbar = ((bool)(resources.GetObject("lstPlayers.HorizontalScrollbar")));
		this.lstPlayers.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lstPlayers.ImeMode")));
		this.lstPlayers.IntegralHeight = ((bool)(resources.GetObject("lstPlayers.IntegralHeight")));
		this.lstPlayers.ItemHeight = ((int)(resources.GetObject("lstPlayers.ItemHeight")));
		this.lstPlayers.Location = ((System.Drawing.Point)(resources.GetObject("lstPlayers.Location")));
		this.lstPlayers.Name = "lstPlayers";
		this.lstPlayers.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lstPlayers.RightToLeft")));
		this.lstPlayers.ScrollAlwaysVisible = ((bool)(resources.GetObject("lstPlayers.ScrollAlwaysVisible")));
		this.lstPlayers.Size = ((System.Drawing.Size)(resources.GetObject("lstPlayers.Size")));
		this.lstPlayers.TabIndex = ((int)(resources.GetObject("lstPlayers.TabIndex")));
		this.lstPlayers.Visible = ((bool)(resources.GetObject("lstPlayers.Visible")));
		// 
		// label2
		// 
		this.label2.AccessibleDescription = resources.GetString("label2.AccessibleDescription");
		this.label2.AccessibleName = resources.GetString("label2.AccessibleName");
		this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("label2.Anchor")));
		this.label2.AutoSize = ((bool)(resources.GetObject("label2.AutoSize")));
		this.label2.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("label2.Dock")));
		this.label2.Enabled = ((bool)(resources.GetObject("label2.Enabled")));
		this.label2.Font = ((System.Drawing.Font)(resources.GetObject("label2.Font")));
		this.label2.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(0)), ((System.Byte)(192)));
		this.label2.Image = ((System.Drawing.Image)(resources.GetObject("label2.Image")));
		this.label2.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label2.ImageAlign")));
		this.label2.ImageIndex = ((int)(resources.GetObject("label2.ImageIndex")));
		this.label2.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("label2.ImeMode")));
		this.label2.Location = ((System.Drawing.Point)(resources.GetObject("label2.Location")));
		this.label2.Name = "label2";
		this.label2.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("label2.RightToLeft")));
		this.label2.Size = ((System.Drawing.Size)(resources.GetObject("label2.Size")));
		this.label2.TabIndex = ((int)(resources.GetObject("label2.TabIndex")));
		this.label2.Text = resources.GetString("label2.Text");
		this.label2.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label2.TextAlign")));
		this.label2.Visible = ((bool)(resources.GetObject("label2.Visible")));
		// 
		// btnPM
		// 
		this.btnPM.AccessibleDescription = resources.GetString("btnPM.AccessibleDescription");
		this.btnPM.AccessibleName = resources.GetString("btnPM.AccessibleName");
		this.btnPM.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnPM.Anchor")));
		this.btnPM.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnPM.BackgroundImage")));
		this.btnPM.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnPM.Dock")));
		this.btnPM.Enabled = ((bool)(resources.GetObject("btnPM.Enabled")));
		this.btnPM.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnPM.FlatStyle")));
		this.btnPM.Font = ((System.Drawing.Font)(resources.GetObject("btnPM.Font")));
		this.btnPM.Image = ((System.Drawing.Image)(resources.GetObject("btnPM.Image")));
		this.btnPM.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnPM.ImageAlign")));
		this.btnPM.ImageIndex = ((int)(resources.GetObject("btnPM.ImageIndex")));
		this.btnPM.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnPM.ImeMode")));
		this.btnPM.Location = ((System.Drawing.Point)(resources.GetObject("btnPM.Location")));
		this.btnPM.Name = "btnPM";
		this.btnPM.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnPM.RightToLeft")));
		this.btnPM.Size = ((System.Drawing.Size)(resources.GetObject("btnPM.Size")));
		this.btnPM.TabIndex = ((int)(resources.GetObject("btnPM.TabIndex")));
		this.btnPM.Text = resources.GetString("btnPM.Text");
		this.btnPM.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnPM.TextAlign")));
		this.btnPM.Visible = ((bool)(resources.GetObject("btnPM.Visible")));
		// 
		// btnKick
		// 
		this.btnKick.AccessibleDescription = resources.GetString("btnKick.AccessibleDescription");
		this.btnKick.AccessibleName = resources.GetString("btnKick.AccessibleName");
		this.btnKick.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnKick.Anchor")));
		this.btnKick.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnKick.BackgroundImage")));
		this.btnKick.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnKick.Dock")));
		this.btnKick.Enabled = ((bool)(resources.GetObject("btnKick.Enabled")));
		this.btnKick.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnKick.FlatStyle")));
		this.btnKick.Font = ((System.Drawing.Font)(resources.GetObject("btnKick.Font")));
		this.btnKick.Image = ((System.Drawing.Image)(resources.GetObject("btnKick.Image")));
		this.btnKick.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnKick.ImageAlign")));
		this.btnKick.ImageIndex = ((int)(resources.GetObject("btnKick.ImageIndex")));
		this.btnKick.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnKick.ImeMode")));
		this.btnKick.Location = ((System.Drawing.Point)(resources.GetObject("btnKick.Location")));
		this.btnKick.Name = "btnKick";
		this.btnKick.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnKick.RightToLeft")));
		this.btnKick.Size = ((System.Drawing.Size)(resources.GetObject("btnKick.Size")));
		this.btnKick.TabIndex = ((int)(resources.GetObject("btnKick.TabIndex")));
		this.btnKick.Text = resources.GetString("btnKick.Text");
		this.btnKick.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnKick.TextAlign")));
		this.btnKick.Visible = ((bool)(resources.GetObject("btnKick.Visible")));
		// 
		// textBox1
		// 
		this.textBox1.AccessibleDescription = resources.GetString("textBox1.AccessibleDescription");
		this.textBox1.AccessibleName = resources.GetString("textBox1.AccessibleName");
		this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("textBox1.Anchor")));
		this.textBox1.AutoSize = ((bool)(resources.GetObject("textBox1.AutoSize")));
		this.textBox1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("textBox1.BackgroundImage")));
		this.textBox1.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("textBox1.Dock")));
		this.textBox1.Enabled = ((bool)(resources.GetObject("textBox1.Enabled")));
		this.textBox1.Font = ((System.Drawing.Font)(resources.GetObject("textBox1.Font")));
		this.textBox1.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("textBox1.ImeMode")));
		this.textBox1.Location = ((System.Drawing.Point)(resources.GetObject("textBox1.Location")));
		this.textBox1.MaxLength = ((int)(resources.GetObject("textBox1.MaxLength")));
		this.textBox1.Multiline = ((bool)(resources.GetObject("textBox1.Multiline")));
		this.textBox1.Name = "textBox1";
		this.textBox1.PasswordChar = ((char)(resources.GetObject("textBox1.PasswordChar")));
		this.textBox1.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("textBox1.RightToLeft")));
		this.textBox1.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("textBox1.ScrollBars")));
		this.textBox1.Size = ((System.Drawing.Size)(resources.GetObject("textBox1.Size")));
		this.textBox1.TabIndex = ((int)(resources.GetObject("textBox1.TabIndex")));
		this.textBox1.Text = resources.GetString("textBox1.Text");
		this.textBox1.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("textBox1.TextAlign")));
		this.textBox1.Visible = ((bool)(resources.GetObject("textBox1.Visible")));
		this.textBox1.WordWrap = ((bool)(resources.GetObject("textBox1.WordWrap")));
		// 
		// label3
		// 
		this.label3.AccessibleDescription = resources.GetString("label3.AccessibleDescription");
		this.label3.AccessibleName = resources.GetString("label3.AccessibleName");
		this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("label3.Anchor")));
		this.label3.AutoSize = ((bool)(resources.GetObject("label3.AutoSize")));
		this.label3.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("label3.Dock")));
		this.label3.Enabled = ((bool)(resources.GetObject("label3.Enabled")));
		this.label3.Font = ((System.Drawing.Font)(resources.GetObject("label3.Font")));
		this.label3.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(0)), ((System.Byte)(192)));
		this.label3.Image = ((System.Drawing.Image)(resources.GetObject("label3.Image")));
		this.label3.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label3.ImageAlign")));
		this.label3.ImageIndex = ((int)(resources.GetObject("label3.ImageIndex")));
		this.label3.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("label3.ImeMode")));
		this.label3.Location = ((System.Drawing.Point)(resources.GetObject("label3.Location")));
		this.label3.Name = "label3";
		this.label3.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("label3.RightToLeft")));
		this.label3.Size = ((System.Drawing.Size)(resources.GetObject("label3.Size")));
		this.label3.TabIndex = ((int)(resources.GetObject("label3.TabIndex")));
		this.label3.Text = resources.GetString("label3.Text");
		this.label3.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label3.TextAlign")));
		this.label3.Visible = ((bool)(resources.GetObject("label3.Visible")));
		// 
		// frmMain
		// 
		this.AccessibleDescription = resources.GetString("$this.AccessibleDescription");
		this.AccessibleName = resources.GetString("$this.AccessibleName");
		this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize")));
		this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll")));
		this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin")));
		this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize")));
		this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
		this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize")));
		this.Controls.Add(this.label3);
		this.Controls.Add(this.textBox1);
		this.Controls.Add(this.btnKick);
		this.Controls.Add(this.btnPM);
		this.Controls.Add(this.label2);
		this.Controls.Add(this.lstPlayers);
		this.Controls.Add(this.Label1);
		this.Controls.Add(this.lblInstructions);
		this.Controls.Add(this.btnBroadcast);
		this.Controls.Add(this.txtBroadcast);
		this.Controls.Add(this.lstStatus);
		this.Enabled = ((bool)(resources.GetObject("$this.Enabled")));
		this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font")));
		this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
		this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
		this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode")));
		this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location")));
		this.MaximizeBox = false;
		this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize")));
		this.Menu = this.mnuMain;
		this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize")));
		this.Name = "frmMain";
		this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft")));
		this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition")));
		this.Text = resources.GetString("$this.Text");
		this.Closing += new System.ComponentModel.CancelEventHandler(this.frmMain_Closing);
		this.Load += new System.EventHandler(this.frmMain_Load);
		this.ResumeLayout(false);
 
	}
 
#endregion
 
#region " Standard Menu Code "
 
    // This code simply shows the About form.
    private void mnuAbout_Click(object sender, System.EventArgs e) 
	{
        // Open the About form in Dialog Mode
        frmAbout frm = new frmAbout();
        frm.ShowDialog(this);
        frm.Dispose();
    }
 
    // This code will close the form.
    private void mnuExit_Click(object sender, System.EventArgs e) 
	{
        // Close the current form
        this.Close();
    }
 
#endregion
 
    const int PORT_NUM = 10000;
    private Hashtable clients = new Hashtable();
    private TcpListener listener;
    private Thread listenerThread;
 
    // This subroutine sends a message to all attached clients
    private void Broadcast(string strMessage)
	{
		UserConnection client;
        // All entries in the clients Hashtable are UserConnection so it is possible
        // to assign it safely.
        foreach(DictionaryEntry entry in clients)
		{
            client = (UserConnection) entry.Value;
            client.SendData(strMessage);
        }
    }
 
    // This subroutine sends the contents of the Broadcast textbox to all clients, if
    // it is not empty, and clears the textbox
    private void btnBroadcast_Click(object sender, System.EventArgs e) 
	{
        if (txtBroadcast.Text != "")
		{
            UpdateStatus("Broadcasting: " + txtBroadcast.Text);
            Broadcast("BROAD|" + txtBroadcast.Text);
            txtBroadcast.Text = string.Empty;
        }
    }
 
    // This subroutine checks to see if username already exists in the clients 
    // Hashtable.  if it does, send a REFUSE message, otherwise confirm with a JOIN.
    private void ConnectUser(string userName, UserConnection sender)
	{
		if (clients.Contains(userName))
		{
			ReplyToSender("REFUSE", sender);
		}
		else 
		{
			sender.Name = userName;
			UpdateStatus(userName + " has joined the chat.");
			clients.Add(userName, sender);
			lstPlayers.Items.Add(sender.Name);
			// Send a JOIN to sender, and notify all other clients that sender joined
			ReplyToSender("JOIN", sender);
			SendToClients("CHAT|" + sender.Name + " has joined the chat.", sender);
		}
    }
 
    // This subroutine notifies other clients that sender left the chat, and removes
    // the name from the clients Hashtable
    private void DisconnectUser(UserConnection sender)
	{
        UpdateStatus(sender.Name + " has left the chat.");
        SendToClients("CHAT|" + sender.Name + " has left the chat.", sender);
        clients.Remove(sender.Name);
		lstPlayers.Items.Remove(sender.Name);
    }
 
    // This subroutine is used a background listener thread to allow reading incoming
    // messages without lagging the user interface.
    private void DoListen()
	{
        try {
            // Listen for new connections.
            listener = new TcpListener(System.Net.IPAddress.Any, PORT_NUM);
            listener.Start();
 
			do
			{
				// Create a new user connection using TcpClient returned by
				// TcpListener.AcceptTcpClient()
				UserConnection client = new UserConnection(listener.AcceptTcpClient());
				// Create an event handler to allow the UserConnection to communicate
				// with the window.
				client.LineReceived += new LineReceive(OnLineReceived);
				//AddHandler client.LineReceived, AddressOf OnLineReceived;
				UpdateStatus("new connection found: waiting for log-in");
			}while(true);
        } 
		catch(Exception ex){
			//MessageBox.Show(ex.ToString());
        }
    }
 
    // When the window closes, stop the listener.
    private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e) //base.Closing;
	{
        listener.Stop();
    }
 
    // Start the background listener thread.
    private void frmMain_Load(object sender, System.EventArgs e) 
	{
        listenerThread = new Thread(new ThreadStart(DoListen));
        listenerThread.Start();
        UpdateStatus("Listener started");
    }
 
    // Concatenate all the client names and send them to the user who requested user list
    private void ListUsers(UserConnection sender)
	{
        UserConnection client;       
        string strUserList;
        UpdateStatus("Sending " + sender.Name + " a list of users online.");
        strUserList = "LISTUSERS";
        // All entries in the clients Hashtable are UserConnection so it is possible
        // to assign it safely.
 
        foreach(DictionaryEntry entry in clients)
		{
            client = (UserConnection) entry.Value;
            strUserList = strUserList + "|" + client.Name;
        }
 
        // Send the list to the sender.
        ReplyToSender(strUserList, sender);
    }
 
    // This is the event handler for the UserConnection when it receives a full line.
    // Parse the cammand and parameters and take appropriate action.
    private void OnLineReceived(UserConnection sender, string data)
	{
        string[] dataArray;
        // Message parts are divided by "|"  Break the string into an array accordingly.
		// Basically what happens here is that it is possible to get a flood of data during
		// the lock where we have combined commands and overflow
		// to simplify this proble, all I do is split the response by char 13 and then look
		// at the command, if the command is unknown, I consider it a junk message
		// and dump it, otherwise I act on it
		dataArray = data.Split((char) 13);
        dataArray = dataArray[0].Split((char) 124);
 
        // dataArray(0) is the command.
        switch( dataArray[0])
		{
            case "CONNECT":
                ConnectUser(dataArray[1], sender);
				break;
            case "CHAT":
                SendChat(dataArray[1], sender);
				break;
            case "DISCONNECT":
                DisconnectUser(sender);
				break;
            case "REQUESTUSERS":
                ListUsers(sender);
				break;
            default: 
                // Message is junk do nothing with it.
				break;
        }
    }
 
    // This subroutine sends a response to the sender.
    private void ReplyToSender(string strMessage, UserConnection sender)
	{
        sender.SendData(strMessage);
    }
 
    // Send a chat message to all clients except sender.
    private void SendChat(string message, UserConnection sender)
	{
        UpdateStatus(sender.Name + ": " + message);
        SendToClients("CHAT|" + sender.Name + ": " + message, sender);
    }
 
    // This subroutine sends a message to all attached clients except the sender.
    private void SendToClients(string strMessage, UserConnection sender)
	{
        UserConnection client;
        // All entries in the clients Hashtable are UserConnection so it is possible
        // to assign it safely.
        foreach(DictionaryEntry entry in clients)
		{
            client = (UserConnection) entry.Value;
            // Exclude the sender.
            if (client.Name != sender.Name)
			{
                client.SendData(strMessage);
            }
        }
    }
 
    // This subroutine adds line to the Status listbox
    private void UpdateStatus(string statusMessage)
	{
        lstStatus.Items.Add(statusMessage);
    }
}



UserConnection.cs Code:

using System;
using System.Net.Sockets;
using System.Text;
using System.IO;
 
public delegate void LineReceive(UserConnection sender, string Data);
 
// The UserConnection class encapsulates the functionality of a TcpClient connection
// with streaming for a single user.
 
public class UserConnection
{
    const int READ_BUFFER_SIZE = 255;
    // Overload the new operator to set up a read thread.
    public UserConnection(TcpClient client)
	{
        this.client = client;
        // This starts the asynchronous read thread.  The data will be saved into
        // readBuffer.
        this.client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReceiver), null);
    }
 
    private TcpClient client;
    private byte[] readBuffer = new byte[READ_BUFFER_SIZE];
    private string strName;
 
    // The Name property uniquely identifies the user connection.
    public string Name
	{
        get {
            return strName;
        }
        set {
            strName = value;
        }
    }
 
    public event LineReceive LineReceived;
 
    // This subroutine uses a StreamWriter to send a message to the user.
    public void SendData(string Data)
	{
        //lock ensure that no other threads try to use the stream at the same time.
        lock (client.GetStream())
		{
			StreamWriter writer = new StreamWriter(client.GetStream());
			writer.Write(Data + (char) 13 + (char) 10);
			// Make sure all data is sent now.
			writer.Flush();
		}
    }
 
    // This is the callback function for TcpClient.GetStream.Begin. It begins an 
    // asynchronous read from a stream.
    private void StreamReceiver(IAsyncResult ar)
	{
        int BytesRead;
        string strMessage;
 
        try 
		{
            // Ensure that no other threads try to use the stream at the same time.
			lock (client.GetStream())
			{
				// Finish asynchronous read into readBuffer and get number of bytes read.
				BytesRead = client.GetStream().EndRead(ar);
			}
            // Convert the byte array the message was saved into, minus one for the
            // Chr(13).
            strMessage = Encoding.ASCII.GetString(readBuffer, 0, BytesRead - 1);
            LineReceived(this, strMessage);
            // Ensure that no other threads try to use the stream at the same time.
			lock (client.GetStream())
			{
				// Start a new asynchronous read into readBuffer.
				client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReceiver), null);
			}
		} 
		catch( Exception e){
        }
    }
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox