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 (); } <summary>
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
</summary>
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 ();
}
<summary>
Start listening.
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
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;
} <summary>
Receiving client connections
</summary>
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));
} } <summary>
Process received client information
</summary>
<param name= "UserState" > Client Information </param>
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] && user.username!= splitstring[1])
{
Sendtoclient (Target, "talk," + User.username + "," + talkstring);
Break
}
}
Break
Default
Additemtolistbox ("What meaning AH:" + receivestring);
Break
}
}
} <summary>
Send messages to all customers
</summary>
<param name= "User" > Specify which user to send </param>
<param name= "message" > Information content </param>
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 < Userlist.count; i++)
{
Sendtoclient (User, "login," + userlist[i].username);
}
Put yourself online and send it to all clients
for (int i = 0; i < Userlist.count; i++)
{
if (user.username!= userlist[i].username)
{
Sendtoclient (Userlist[i], "login," + user.username);
}
}
}
else if (Command = = "Logout")
{
for (int i = 0; i < Userlist.count; i++)
{
if (userlist[i].username!= user.username)
{
Sendtoclient (Userlist[i], message);
}
}
}
} <summary>
Send Message to User
</summary>
<param name= "User" > Specify which user to send </param>
<param name= "message" > Information content </param>
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);
<summary>
Append state information to the listbox
</summary>
<param name= "str" > Information to append </param>
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 ();
}
} <summary>
Stop listening
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
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 >= 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 } } } |