asp.net based on C # socket Chat program (one server, multiple clients)

Source: Internet
Author: User
Tags readline static class

Part of the code:

Namespaces:

The code is as follows Copy Code

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

MainForm.cs

The code is as follows Copy Code

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;
Using System.Net.Sockets;
Using System.Threading;
Using System.IO;

Namespace Syncchatserver
{
public partial class Mainform:form
{
<summary>
Save all users of a connection
</summary>
Private list<user> userlist = new list<user> ();

<summary>
Server IP Address
</summary>;
private string ServerIP;

<summary>
Listening port
</summary>
private int port;
Private TcpListener MyListener;

<summary>
Whether to exit all incoming threads normally
</summary>
BOOL Isnormalexit = false;

Public MainForm ()
{
InitializeComponent ();
Lst_state.horizontalscrollbar = true;
btn_stop.enabled = false;
Setserveripandport ();
}

&lt;summary&gt;


Set IP and port based on the contents of the text file ' ServerIPAndPort.txt ' of the current program directory


Format: 127.0.0.1:8885


&lt;/summary&gt;


private void Setserveripandport ()


{


FileStream fs = new FileStream ("ServerIPAndPort.txt", FileMode.Open);


StreamReader sr = new StreamReader (FS);


String ipandport = Sr. ReadLine ();


ServerIP = Ipandport.split (': ') [0]; Set IP


Port = Int. Parse (Ipandport.split (': ') [1]); Set port


Sr. Close ();


Fs. Close ();


}




&lt;summary&gt;


Start listening.


&lt;/summary&gt;


&lt;param name= "Sender" &gt;&lt;/param&gt;


&lt;param name= "E" &gt;&lt;/param&gt;


private void Btn_start_click (object sender, EventArgs e)


{


MyListener = new TcpListener (Ipaddress.parse (ServerIP), port);


Mylistener.start ();


Additemtolistbox (String. Format ("Start monitoring client connections in {0}:{1}", ServerIP, Port));


Create a Thread Supervisor Client connection request


Thread mythread = new Thread (listenclientconnect);


Mythread.start ();


btn_start.enabled = false;


Btn_stop.enabled = true;


}

&lt;summary&gt;


Receiving client connections


&lt;/summary&gt;


private void Listenclientconnect ()


{


TcpClient newclient = null;


while (true)


{


Try


{


Newclient = Mylistener.accepttcpclient ();


}


Catch


{


AcceptTcpClient () generates an exception when you click ' Stop listening ' or exit this form


So you can use this exception to exit the loop


Break


}


Every time a client connection is received, a corresponding thread is created to iterate over the information sent by the client;


User user = new user (newclient);


Thread threadreceive = new Thread (receivedata);


Threadreceive.start (user);


Userlist.add (user);


Additemtolistbox (String. Format ("[{0}] enter", NewClient.Client.RemoteEndPoint));


Additemtolistbox (String. Format ("Current number of connected users: {0}", Userlist.count));


}

}

&lt;summary&gt;


Process received client information


&lt;/summary&gt;


&lt;param name= "UserState" &gt; Client Information &lt;/param&gt;


private void Receivedata (object userState)


{


User user = (user) userState;


TcpClient client = user.client;


while (Isnormalexit = = False)


{


string receivestring = null;


Try


{


Reads a string from the network stream, this method automatically determines the string length prefix


receivestring = User.br.ReadString ();


}


catch (Exception)


{


if (Isnormalexit = = False)


{


Additemtolistbox (String. Format ("lost contact with [{0}], terminated to receive this user information", client. Client.remoteendpoint));


Removeuser (user);


}


Break


}


Additemtolistbox (String. Format ("from [{0}]:{1}", user.client.client.remoteendpoint,receivestring));


string[] splitstring = Receivestring.split (', ');


Switch (splitstring[0])


{


Case "Login":


User.username = splitstring[1];


Sendtoallclient (user,receivestring);


Break


Case "Logout":


Sendtoallclient (user,receivestring);


Removeuser (user);


Return


Case "Talk":


String talkstring = Receivestring.substring (splitstring[0]. Length + splitstring[1]. Length + 2);


Additemtolistbox (String. Format ("{0} to {1}" says: {2} ", user.username,splitstring[1],talkstring));


Sendtoclient (User, "talk," + User.username + "," + talkstring);


foreach (User target in userlist)


{


if (Target.username = = splitstring[1] &amp;&amp; user.username!= splitstring[1])


{


Sendtoclient (Target, "talk," + User.username + "," + talkstring);


Break


}


}


Break


Default


Additemtolistbox ("What meaning AH:" + receivestring);


Break


}


}


}

&lt;summary&gt;


Send messages to all customers


&lt;/summary&gt;


&lt;param name= "User" &gt; Specify which user to send &lt;/param&gt;


&lt;param name= "message" &gt; Information content &lt;/param&gt;


private void sendtoallclient (user user, String message)


{


string command = message. Split (', ') [0]. ToLower ();


if (Command = = "Login")


{


Get all client online information to the currently logged-on user


for (int i = 0; i &lt; Userlist.count; i++)


{


Sendtoclient (User, "login," + userlist[i].username);


}


Put yourself online and send it to all clients


for (int i = 0; i &lt; Userlist.count; i++)


{


if (user.username!= userlist[i].username)


{


Sendtoclient (Userlist[i], "login," + user.username);


}


}


}


else if (Command = = "Logout")


{


for (int i = 0; i &lt; Userlist.count; i++)


{


if (userlist[i].username!= user.username)


{


Sendtoclient (Userlist[i], message);


}


}


}


}

&lt;summary&gt;


Send Message to User


&lt;/summary&gt;


&lt;param name= "User" &gt; Specify which user to send &lt;/param&gt;


&lt;param name= "message" &gt; Information content &lt;/param&gt;


private void sendtoclient (user user, String message)


{


Try


{


Writes a string to the network stream, which automatically appends the string length prefix


User.bw.Write (message);


User.bw.Flush ();


Additemtolistbox (String. Format ("Send to [{0}]: {1}", User.username, message));


}


Catch


{


Additemtolistbox (String. Format ("Send information to [{0}] failed", user.username));


}


}

<summary>
removing users from
</summary>
<param name= "User" > Specify the user to remove </param>
private void Removeuser (user user)
{
Userlist.remove (user);
User. Close ();
Additemtolistbox (String. Format ("Current number of connected users: {0}", Userlist.count));
}

Private delegate void Additemtolistboxdelegate (String str);


&lt;summary&gt;


Append state information to the listbox


&lt;/summary&gt;


&lt;param name= "str" &gt; Information to append &lt;/param&gt;


private void Additemtolistbox (String str)


{


if (lst_state.invokerequired)


{


Additemtolistboxdelegate d = additemtolistbox;


Lst_state.invoke (d, str);


}


Else


{


LST_STATE.ITEMS.ADD (str);


Lst_state.selectedindex = lst_state.items.count-1;


Lst_state.clearselected ();


}


}

&lt;summary&gt;


Stop listening


&lt;/summary&gt;


&lt;param name= "Sender" &gt;&lt;/param&gt;


&lt;param name= "E" &gt;&lt;/param&gt;


private void Btn_stop_click (object sender, EventArgs e)


{


Additemtolistbox ("Start stopping the service, and then the user quits!") ");


Isnormalexit = true;


for (int i = userlist.count-1 i &gt;= 0; i--)


{


Removeuser (Userlist[i]);


}


Causes mylistener.accepttcpclient () to exit the listener thread by stopping listening


Mylistener.stop ();


Btn_start.enabled = true;


btn_stop.enabled = false;


}

<summary>
Events that are triggered when a window is closed
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
private void Mainform_formclosing (object sender, FormClosingEventArgs e)
{
if (MyListener!= null)
Btn_stop.performclick (); The Click event that raised the Btn_stop
}
}
}

Code fragment:

The code is as follows Copy Code
&lt;summary&gt;


Set IP and port based on the contents of the text file ' ServerIPAndPort.txt ' of the current program directory


Format: 127.0.0.1:8885


&lt;/summary&gt;


private void Setserveripandport ()


{


FileStream fs = new FileStream ("ServerIPAndPort.txt", FileMode.Open);


StreamReader sr = new StreamReader (FS);


String ipandport = Sr. ReadLine ();


ServerIP = Ipandport.split (': ') [0]; Set IP


Port = Int. Parse (Ipandport.split (': ') [1]); Set port


Sr. Close ();


Fs. Close ();


}








&lt;summary&gt;


Start listening.


&lt;/summary&gt;


&lt;param name= "Sender" &gt;&lt;/param&gt;


&lt;param name= "E" &gt;&lt;/param&gt;


private void Btn_start_click (object sender, EventArgs e)


{


MyListener = new TcpListener (Ipaddress.parse (ServerIP), port);


Mylistener.start ();


Additemtolistbox (String. Format ("Start monitoring client connections in {0}:{1}", ServerIP, Port));


Create a Thread Supervisor Client connection request


Thread mythread = new Thread (listenclientconnect);


Mythread.start ();


btn_start.enabled = false;


Btn_stop.enabled = true;


}





&lt;summary&gt;


Receiving client connections


&lt;/summary&gt;


private void Listenclientconnect ()


{


TcpClient newclient = null;


while (true)


{


Try


{


Newclient = Mylistener.accepttcpclient ();


}


Catch


{


AcceptTcpClient () generates an exception when you click ' Stop listening ' or exit this form


So you can use this exception to exit the loop


Break


}


Every time a client connection is received, a corresponding thread is created to iterate over the information sent by the client;


User user = new user (newclient);


Thread threadreceive = new Thread (receivedata);


Threadreceive.start (user);


Userlist.add (user);


Additemtolistbox (String. Format ("[{0}] enter", NewClient.Client.RemoteEndPoint));


Additemtolistbox (String. Format ("Current number of connected users: {0}", Userlist.count));


}





}





&lt;summary&gt;


Process received client information


&lt;/summary&gt;


&lt;param name= "UserState" &gt; Client Information &lt;/param&gt;


private void Receivedata (object userState)


{


User user = (user) userState;


TcpClient client = user.client;


while (Isnormalexit = = False)


{


string receivestring = null;


Try


{


Reads a string from the network stream, this method automatically determines the string length prefix


receivestring = User.br.ReadString ();


}


catch (Exception)


{


if (Isnormalexit = = False)


{


Additemtolistbox (String. Format ("lost contact with [{0}], terminated to receive this user information", client. Client.remoteendpoint));


Removeuser (user);


}


Break


}


Additemtolistbox (String. Format ("from [{0}]:{1}", user.client.client.remoteendpoint,receivestring));


string[] splitstring = Receivestring.split (', ');


Switch (splitstring[0])


{


Case "Login":


User.username = splitstring[1];


Sendtoallclient (user,receivestring);


Break


Case "Logout":


Sendtoallclient (user,receivestring);


Removeuser (user);


Return


Case "Talk":


String talkstring = Receivestring.substring (splitstring[0]. Length + splitstring[1]. Length + 2);


Additemtolistbox (String. Format ("{0} to {1}" says: {2} ", user.username,splitstring[1],talkstring));


Sendtoclient (User, "talk," + User.username + "," + talkstring);


foreach (User target in userlist)


{


if (Target.username = = splitstring[1] &amp;&amp; user.username!= splitstring[1])


{


Sendtoclient (Target, "talk," + User.username + "," + talkstring);


Break


}


}


Break


Default


Additemtolistbox ("What meaning AH:" + receivestring);


Break


}


}


}

User.cs

The code is as follows Copy Code

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Net.Sockets;
Using System.IO;

Namespace Syncchatserver
{
    class User
    {
         public tcpclient Client {get; private set;}
        public binaryreader br {get; private set;}
        public binarywriter bw {get; private set;}
        public string UserName {get; set;}

        public User (tcpclient client)
         {
            this.client = client;
            NetworkStream networkstream = client. GetStream ();
            br = new BinaryReader (NetworkStream);
            bw = new BinaryWriter (NetworkStream);
       }

public void Close ()
{
Br. Close ();
Bw. Close ();
Client. Close ();
}

}
}

Program.cs

The code is as follows Copy Code

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Windows.Forms;

Namespace Syncchatserver
{
Static Class Program
{
<summary>
The main entry point for the application.
</summary>
[STAThread]
static void Main ()
{
Application.enablevisualstyles ();
Application.setcompatibletextrenderingdefault (FALSE);
Application.Run (New MainForm ());
}
}
}

Main.cs

The code is as follows Copy Code

Namespace Syncchatserver
{
Partial class MainForm
{
<summary>
The required designer variable.
</summary>
Private System.ComponentModel.IContainer components = null;

       ///<summary>
       / Clean up all resources that are in use.
       ///</summary>
        ///<param name= "disposing" > if the managed resource should be freed, true; otherwise, false. </param>
        protected override void Dispose (bool disposing)
        {
             if (disposing && (components!= null))
             {
                Components. Dispose ();
           }
            Base. Dispose (disposing);
       }

Code generated #region the Windows forms Designer

&lt;summary&gt;


Designer supports the required methods-No


Use the Code Editor to modify the contents of this method.


&lt;/summary&gt;


private void InitializeComponent ()


{


This.groupbox1 = new System.Windows.Forms.GroupBox ();


This.lst_state = new System.Windows.Forms.ListBox ();


This.btn_start = new System.Windows.Forms.Button ();


This.btn_stop = new System.Windows.Forms.Button ();


This.groupBox1.SuspendLayout ();


This. SuspendLayout ();


//


GroupBox1


//


THIS.GROUPBOX1.CONTROLS.ADD (this.lst_state);


This.groupBox1.Location = new System.Drawing.Point (12, 12);


This.groupBox1.Name = "GroupBox1";


This.groupBox1.Size = new System.Drawing.Size (523, 327);


This.groupBox1.TabIndex = 0;


This.groupBox1.TabStop = false;


This.groupBox1.Text = "state information";


//


Lst_state


//


This.lst_State.Dock = System.Windows.Forms.DockStyle.Fill;


This.lst_State.FormattingEnabled = true;


This.lst_State.ItemHeight = 12;


This.lst_State.Location = new System.Drawing.Point (3, 17);


This.lst_State.Name = "Lst_state";


This.lst_State.Size = new System.Drawing.Size (517, 304);


This.lst_State.TabIndex = 0;


//


Btn_start


//


This.btn_Start.Location = new System.Drawing.Point (126, 346);


This.btn_Start.Name = "Btn_start";


This.btn_Start.Size = new System.Drawing.Size (75, 23);


This.btn_Start.TabIndex = 1;


This.btn_Start.Text = "Start listening";


This.btn_Start.UseVisualStyleBackColor = true;


This.btn_Start.Click + = new System.EventHandler (This.btn_start_click);


//


Btn_stop


//


This.btn_Stop.Location = new System.Drawing.Point (322, 346);


This.btn_Stop.Name = "Btn_stop";


This.btn_Stop.Size = new System.Drawing.Size (75, 23);


This.btn_Stop.TabIndex = 2;


This.btn_Stop.Text = "Stop Listening";


This.btn_Stop.UseVisualStyleBackColor = true;


This.btn_Stop.Click + = new System.EventHandler (This.btn_stop_click);


//


MainForm


//


This. Autoscaledimensions = new System.Drawing.SizeF (6F, 12F);


This. AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;


This. ClientSize = new System.Drawing.Size (547, 375);


This. Controls.Add (This.btn_stop);


This. Controls.Add (This.btn_start);


This. Controls.Add (This.groupbox1);


This. Name = "MainForm";


This. Text = "Syncchatserver";


This. FormClosing + = new System.Windows.Forms.FormClosingEventHandler (this. mainform_formclosing);


This.groupBox1.ResumeLayout (FALSE);


This. ResumeLayout (FALSE);

}

#endregion

Private System.Windows.Forms.GroupBox GroupBox1;
Private System.Windows.Forms.ListBox lst_state;
Private System.Windows.Forms.Button Btn_start;
Private System.Windows.Forms.Button btn_stop;
}
}

The above is not complete code fragment, because the code too much here to paste out certainly dazzling.

Have a friend in need or download the source to see

Click to download source files

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.