C # multiplayer chat program

Source: Internet
Author: User

Using System;
Using System. Drawing;
Using System. Collections;
Using System. ComponentModel;
Using System. Windows. Forms;
Using System. Data;
Using System. Threading;
Using System. Net. Sockets;
Using System. Net;
Namespace Chat_Server
{
///
/// Summary of Form1.
///
Public class Form1: System. Windows. Forms. Form
{
///
/// Required designer variables.
///
Private System. ComponentModel. Container components = null;

 

Static int listenport = 6666;
Socket clientsocket;
Private System. Windows. Forms. ListBox lbClients;
ArrayList clients;
Private System. Windows. Forms. Button button1;
Thread clientservice;
Private System. Windows. Forms. Label label1;
Thread threadListen;

Public Form1 ()
{

InitializeComponent ();

}

///
/// Clear all resources in use.
///
Protected override void Dispose (bool disposing)
{
If (disposing)
{

If (clientservice! = Null)
{
Clientservice. Abort ();
}
If (threadListen! = Null)
{
Try
{
ThreadListen. Abort ();
}
Catch (Exception ex)
{
ThreadListen = null;
}
}

If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );

}

# Region code generated by Windows Form Designer
///
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
///
Private void InitializeComponent ()
{
This. lbClients = new System. Windows. Forms. ListBox ();
This. button1 = new System. Windows. Forms. Button ();
This. label1 = new System. Windows. Forms. Label ();
This. SuspendLayout ();
//
// LbClients
//
This. lbClients. ItemHeight = 12;
This. lbClients. Location = new System. Drawing. Point (16, 24 );
This. lbClients. Name = "lbClients ";
This. lbClients. Size = new System. Drawing. Size (184,268 );
This. lbClients. TabIndex = 0;
//
// Button1
//
This. button1.Location = new System. Drawing. Point (272, 56 );
This. button1.Name = "button1 ";
This. button1.TabIndex = 1;
This. button1.Text = "button1 ";
This. button1.Click + = new System. EventHandler (this. button#click );
//
// Label1
//
This. label1.Location = new System. Drawing. Point (240,136 );
This. label1.Name = "label1 ";
This. label1.Size = new System. Drawing. Size (120, 32 );
This. label1.TabIndex = 2;
This. label1.Text = "label1 ";
//
// Form1
//
This. AutoScaleBaseSize = new System. Drawing. Size (6, 14 );
This. ClientSize = new System. Drawing. Size (368,309 );
This. Controls. Add (this. label1 );
This. Controls. Add (this. button1 );
This. Controls. Add (this. lbClients );
This. Name = "Form1 ";
This. Text = "Form1 ";
This. Load + = new System. EventHandler (this. form#load );
This. ResumeLayout (false );

}
# Endregion

///
/// Main entry point of the application.
///
[STAThread]
Static void Main ()
{
Application. Run (new Form1 ());
}

Private void StartListening ()
{
TcpListener listener = new TcpListener (listenport );
Listener. Start ();
Label1.Text = "listening ....";
While (true)
{
Try
{

Socket s = listener. AcceptSocket ();
Clientsocket = s;
Clientservice = new Thread (new ThreadStart (ServiceClient ));
Clientservice. Start ();
}
Catch (Exception ex)
{
MessageBox. Show ("listening Error:" + ex. Message );
}
}
}
Private void ServiceClient ()
{
Socket client = clientsocket;
Bool keepalive = true;

While (keepalive)
{
Byte [] buffer = new Byte [1024];
Int bufLen = 0;
Try
{
BufLen = client. Available;

Client. Receive (buffer, 0, bufLen, SocketFlags. None );
If (bufLen = 0)
Continue;
}
Catch (Exception ex)
{
MessageBox. Show ("Receive Error:" + ex. Message );
Return;
}

String clientcommand = System. Text. Encoding. ASCII. GetString (buffer). Substring (0, bufLen );

String [] tokens = clientcommand. Split (new Char [] {'| '});
Console. WriteLine (clientcommand );

If (tokens [0] = "CONN ")
{
For (int n = 0; n {
Client cl = (Client) clients [n];
SendToClient (cl, "JOIN |" + tokens [1]);
}
EndPoint ep = client. RemoteEndPoint;
Client c = new Client (tokens [1], ep, clientservice, client );

String message = "LIST |" + GetChatterList () + "\ r \ n ";
SendToClient (c, message );

Clients. Add (c );

LbClients. Items. Add (c );

}
If (tokens [0] = "CHAT ")
{
For (int n = 0; n {
Client cl = (Client) clients [n];
SendToClient (cl, clientcommand );
}
}
If (tokens [0] = "PRIV ")
{
String destclient = tokens [3];
For (int n = 0; n {
Client cl = (Client) clients [n];
If (cl. Name. CompareTo (tokens [3]) = 0)
SendToClient (cl, clientcommand );
If (cl. Name. CompareTo (tokens [1]) = 0)
SendToClient (cl, clientcommand );
}
}
If (tokens [0] = "GONE ")
{
Int remove = 0;
Bool found = false;
Int c = clients. Count;
For (int n = 0; n {
Client cl = (Client) clients [n];
SendToClient (cl, clientcommand );
If (cl. Name. CompareTo (tokens [1]) = 0)
{
Remove = n;
Found = true;
LbClients. Items. Remove (cl );
}
}
If (found)
Clients. RemoveAt (remove );
Client. Close ();
Keepalive = false;
}
}
}

Private string GetChatterList ()
{
String result = "";

For (int I = 0; I {
Result + = (Client) clients [I]). Name + "| ";
}
Return result;

}

Private void SendToClient (Client cl, string clientCommand)
{
Byte [] message = System. Text. Encoding. ASCII. GetBytes (clientCommand );
Socket s = cl. Sock;
If (s. Connected)
{
S. Send (message, message. Length, 0 );
}
}

Private void Form1_Load (object sender, System. EventArgs e)
{
Clients = new ArrayList ();
}

Private void button#click (object sender, System. EventArgs e)
{
ThreadListen = new Thread (new ThreadStart (StartListening ));
ThreadListen. Start ();
}
}
}

 

 

******** ************/

/************************** Stored in the chatServer project *********/

Using System;
Using System. Threading;

Namespace Chat_Server
{
Using System. Net. Sockets;
Using System. Net;

///
/// Summary of the Client.
///
Public class Client
{
Private Thread clthread;
Private EndPoint endpoint;
Private string name;
Private Socket sock;

Public Client (string _ name, EndPoint _ endpoint, Thread _ thread, Socket _ sock)
{
// TODO: add the constructor logic here
Clthread = _ thread;
Endpoint = _ endpoint;
Name = _ name;
Sock = _ sock;
}

Public override string ToString ()
{
Return endpoint. ToString () + ":" + name;
}

Public Thread CLThread
{
Get {return clthread ;}
Set {clthread = value ;}
}

Public EndPoint Host
{
Get {return endpoint ;}
Set {endpoint = value ;}
}

Public string Name
{
Get {return name ;}
Set {name = value ;}
}

Public Socket Sock
{
Get {return sock ;}
Set {sock = value ;}
}
}
}

/***************************** ChatClient ********* ***************************/

Using System;
Using System. Drawing;
Using System. Collections;
Using System. ComponentModel;
Using System. Windows. Forms;
Using System. Data;

Using System. IO;
Using System. Net;
Using System. Net. Sockets;
Using System. Threading;

Namespace Chat_Client
{
///
/// Summary of Form1.
///
Public class Form1: System. Windows. Forms. Form
{
Private System. Windows. Forms. CheckBox checkBox1;
Private System. Windows. Forms. StatusBar statusBar1;

NetworkStream ns;
StreamReader sr;
TcpClient clientsocket;
Bool connected;
Thread receive;
String serveraddress = "219.228.231.85 ";
Int serverport = 6666;

Private System. Windows. Forms. RichTextBox rtbChatIn;
Private System. Windows. Forms. ListBox lbChatters;
Private System. Windows. Forms. TextBox ChatOut;
Private System. Windows. Forms. Button btnDisconnect;
Private System. Windows. Forms. Button btnSend;
Private System. Windows. Forms. TextBox clientName;

String clientname;
Private System. Windows. Forms. Button btnConnect;

Private System. ComponentModel. Container components = null;

Public Form1 ()
{

InitializeComponent ();

}

///
/// Clear all resources in use.
///
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (receive! = Null)
{
QuitChat ();
}
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

# Region code generated by Windows Form Designer
///
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
///
Private void InitializeComponent ()
{
This. lbChatters = new System. Windows. Forms. ListBox ();
This. rtbChatIn = new System. Windows. Forms. RichTextBox ();
This. checkBox1 = new System. Windows. Forms. CheckBox ();
This. ChatOut = new System. Windows. Forms. TextBox ();
This. btnSend = new System. Windows. Forms. Button ();
This. statusBar1 = new System. Windows. Forms. StatusBar ();
This. btnDisconnect = new System. Windows. Forms. Button ();
This. clientName = new System. Windows. Forms. TextBox ();
This. btnConnect = new System. Windows. Forms. Button ();
This. SuspendLayout ();
//
// LbChatters
//
This. lbChatters. ItemHeight = 12;
This. lbChatters. Location = new System. Drawing. Point (32, 40 );
This. lbChatters. Name = "lbChatters ";
This. lbChatters. Size = new System. Drawing. Size (112,172 );
This. lbChatters. TabIndex = 0;
//
// RtbChatIn
//
This. rtbChatIn. Location = new System. Drawing. Point (160, 40 );
This. rtbChatIn. Name = "rtbChatIn ";
This. rtbChatIn. Size = new System. Drawing. Size (208,176 );
This. rtbChatIn. TabIndex = 2;
This. rtbChatIn. Text = "";
//
// CheckBox1
//
This. checkBox1.Location = new System. Drawing. Point (16,248 );
This. checkBox1.Name = "checkBox1 ";
This. checkBox1.TabIndex = 3;
This. checkBox1.Text = "checkBox1 ";
//
// ChatOut
//
This. ChatOut. Location = new System. Drawing. Point (136,248 );
This. ChatOut. Name = "ChatOut ";
This. ChatOut. Size = new System. Drawing. Size (136, 21 );
This. ChatOut. TabIndex = 4;
This. ChatOut. Text = "message ";
//
// BtnSend
//
This. btnSend. Location = new System. Drawing. Point (336,248 );
This. btnSend. Name = "btnSend ";
This. btnSend. TabIndex = 5;
This. btnSend. Text = "send ";
This. btnSend. Click + = new System. EventHandler (this. btnSend_Click );
//
// StatusBar1
//
This. statusBar1.Location = new System. Drawing. Point (0,287 );
This. statusBar1.Name = "statusBar1 ";
This. statusBar1.Size = new System. Drawing. Size (464, 22 );
This. statusBar1.TabIndex = 6;
This. statusBar1.Text = "statusBar1 ";
//
// BtnDisconnect
//
This. btnDisconnect. Enabled = false;
This. btnDisconnect. Location = new System. Drawing. Point (392,112 );
This. btnDisconnect. Name = "btnDisconnect ";
This. btnDisconnect. Size = new System. Drawing. Size (64, 32 );
This. btnDisconnect. TabIndex = 7;
This. btnDisconnect. Text = "disconnected ";
This. btnDisconnect. Click + = new System. EventHandler (this. btnDisconnect_Click );
//
// ClientName
//
This. clientName. Location = new System. Drawing. Point (96, 8 );
This. clientName. Name = "clientName ";
This. clientName. TabIndex = 8;
This. clientName. Text = "name ";
//
// BtnConnect
//
This. btnConnect. Location = new System. Drawing. Point (392, 56 );
This. btnConnect. Name = "btnConnect ";
This. btnConnect. Size = new System. Drawing. Size (64, 32 );
This. btnConnect. TabIndex = 9;
This. btnConnect. Text = "Connect ";
This. btnConnect. Click + = new System. EventHandler (this. btnConnect_Click );
//
// Form1
//
This. AutoScaleBaseSize = new System. Drawing. Size (6, 14 );
This. ClientSize = new System. Drawing. Size (464,309 );
This. Controls. Add (this. btnConnect );
This. Controls. Add (this. clientName );
This. Controls. Add (this. btnDisconnect );
This. Controls. Add (this. statusBar1 );
This. Controls. Add (this. btnSend );
This. Controls. Add (this. ChatOut );
This. Controls. Add (this. checkBox1 );
This. Controls. Add (this. rtbChatIn );
This. Controls. Add (this. lbChatters );
This. Name = "Form1 ";
This. Text = "Form1 ";
This. ResumeLayout (false );

}
# Endregion

///
/// Main entry point of the application.
///
[STAThread]
Static void Main ()
{
Application. Run (new Form1 ());
}

Private void EstablishConnection ()
{
StatusBar1.Text = "connecting to server ";

Try
{
Clientsocket = new TcpClient (serveraddress, serverport );
Ns = clientsocket. GetStream ();
Sr = new StreamReader (ns );
Connected = true;

}
Catch (Exception)
{
MessageBox. Show ("cannot connect to the server! "," Error ",
MessageBoxButtons. OK, MessageBoxIcon. Exclamation );
StatusBar1.Text = "disconnected ";
}
}

Private void RegisterWithServer ()
{
LbChatters. Items. Clear ();

Clientname = clientName. Text;
Try
{
String command = "CONN |" + clientname; // + "\ r \ n ";
Byte [] outbytes = System. Text. Encoding. ASCII. GetBytes (command. ToCharArray ());
Ns. Write (outbytes, 0, outbytes. Length );

String serverresponse = sr. ReadLine ();
Serverresponse. Trim ();
String [] tokens = serverresponse. Split ('| ');
If (tokens [0] = "LIST ")
{
StatusBar1.Text = "connected ";
BtnDisconnect. Enabled = true;
}
If (tokens [1]! = "")
{
For (int n = 1; n lbChatters. Items. Add (tokens [n]. Trim (new char [] {'\ R',' \ n '}));
}
This. Text = clientname + ": connected to the server ";

}
Catch (Exception ex)
{
MessageBox. Show ("an error occurred during registration! "+ Ex. Message," error ",
MessageBoxButtons. OK, MessageBoxIcon. Exclamation );
Connected = false;
}
}

Private void ReceiveChat ()
{
Bool keepalive = true;
While (keepalive)
{
Try
{
Byte [] buffer = new Byte [1024]; // 2048 ???
Ns. Read (buffer, 0, buffer. Length );
String chatter = System. Text. Encoding. ASCII. GetString (buffer );
String [] tokens = chatter. Split (new Char [] {'| '});

If (tokens [0] = "CHAT ")
{
RtbChatIn. AppendText (tokens [1]);
// If (logging)
// Logwriter. WriteLine (tokens [1]);
}
If (tokens [0] = "PRIV ")
{
RtbChatIn. AppendText ("Private from ");
RtbChatIn. AppendText (tokens [1]. Trim ());
RtbChatIn. AppendText (tokens [2] + "\ r \ n ");
// If (logging)
//{
// Logwriter. Write ("Private from ");
// Logwriter. Write (tokens [1]. Trim ());
// Logwriter. WriteLine (tokens [2] + "\ r \ n ");
//}
}
If (tokens [0] = "JOIN ")
{
RtbChatIn. AppendText (tokens [1]. Trim ());
RtbChatIn. AppendText ("has joined the Chat \ r \ n ");
// If (logging)
//{
// Logwriter. WriteLine (tokens [1] + "has joined the Chat ");
//}
String newguy = tokens [1]. Trim (new char [] {'\ R',' \ n '});
LbChatters. Items. Add (newguy );
}
If (tokens [0] = "GONE ")
{
RtbChatIn. AppendText (tokens [1]. Trim ());
RtbChatIn. AppendText ("has left the Chat \ r \ n ");
// If (logging)
//{
// Logwriter. WriteLine (tokens [1] + "has left the Chat ");
//}
LbChatters. Items. Remove (tokens [1]. Trim (new char [] {'\ R',' \ n '}));
}
If (tokens [0] = "QUIT ")
{
Ns. Close ();
Clientsocket. Close ();
Keepalive = false;
StatusBar1.Text = "the server has stopped ";
Connected = false;
BtnSend. Enabled = false;
BtnDisconnect. Enabled = false;
}
}
Catch (Exception ){}
}
}

Private void QuitChat ()
{
If (connected)
{
Try
{
String command = "GONE |" + clientname;
Byte [] outbytes = System. Text. Encoding. ASCII. GetBytes (command. ToCharArray ());
Ns. Write (outbytes, 0, outbytes. Length );
Clientsocket. Close ();
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
}
// If (logging)
// Logwriter. Close ();
If (receive! = Null & receive. IsAlive)
Receive. Abort ();
This. Text = "client ";

Connected = false;

}

Private void btnSend_Click (object sender, System. EventArgs e)
{
If (connected)
{
Try
{
String command = "CHAT |" + clientname + ":" + ChatOut. Text + "\ r \ n ";
Byte [] outbytes = System. Text. Encoding. ASCII. GetBytes (command. ToCharArray ());
Ns. Write (outbytes, 0, outbytes. Length );
// Clientsocket. Close ();
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
}
}

Private void btnConnect_Click (object sender, System. EventArgs e)
{
EstablishConnection ();
RegisterWithServer ();
If (connected)
{
Receive = new Thread (new ThreadStart (ReceiveChat ));
Receive. Start ();
}
}

Private void btnDisconnect_Click (object sender, System. EventArgs e)
{
QuitChat ();
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.