C # Asynchronous Communication network chat program development LAN Chat room development

Source: Internet
Author: User

Prepare

This article will use a NuGet exposed component technology to implement a LAN chat program, using the high-performance asynchronous network mechanism provided by the component implementation, eliminating the problem of manually writing the underlying, easy to develop two times, expand their capabilities.

You can download the installation in the NuGet Manager in Visual Studio, or you can enter the following instructions directly in the NuGet console to install:

Install-package hslcommunication

NuGet Installation Tutorial Http://www.cnblogs.com/dathlin/p/7705014.html

QQ Group of Technical Support: 592132877 (the component version update details will be released in the group in the first time)

Summary

There have been a blog about the development of synchronous network communication, synchronous network communication for what kind of scenario, for the client to request data from the server, there must be data return, regardless of success or failure. Address: http://www.cnblogs.com/dathlin/p/7697782.html

and asynchronous network communication is suitable for what situation, suitable for the server for mass data, such as sending messages to all online clients, in order to better explain the implementation mechanism of asynchronous network communication, develop a multi-client LAN Chat program to demonstrate asynchronous operations.

Features are as follows:

    • LAN chat room support multiplayer online, the upper limit depends on the computer performance of the server.
    • Support User name login, support duplicate user name login.
    • Support to display all online client information display, including online time, time, IP address, user name and so on.
    • The server actively sends messages to the client.
    • The support server forces the client to shut down.
    • Support for other people's up and down line information tracking.

This chat program is based on the c-s architecture design, need to create 3 projects, a server project, to relay all the messages, one is the client project, that is, the actual chat program, this project also shows all the online client information, IP address, name.

As for accounts, this time does not use any user name password login mechanism, the use of simple processing, directly enter a name can, of course, you can also change the user name password login mechanism, is not particularly difficult.

Simple chat program does not support the picture, the expression package sent to receive, this part of the implementation is not the same dimensional, this part later conquered the new blog post.

------------> Episode

If more complex functions are needed, such as account login, password modification, versioning, account support Avatar, and so on, a basic template project based on the CS architecture extended by this component, two times for easy two development based on this, the project uses several file management:

Https://github.com/dathlin/ClientServerProject

A c-s template, the template is composed of three parts of the program, a server running program, a client run the program, there is a public component, the implementation of the basic account management functions, version control, software upgrades, Bulletin management, message mass, shared file upload download, batch file transfer function. The specific method of operation can be seen in the demo. One goal of this project is to provide a basic c-s framework for small and medium-sized systems, with clients having four modes, seamless integrated access, WinForm version, WPF version, ASP. NET MVC version, and Android version. It facilitates two development and individual learning of small and medium-sized systems in enterprises.

Reference

All of the feature classes in the log component are in the hslcommunication and hslcommunication.enthernet namespaces, so add them before you use them: both the server program and the client program are added

Using hslcommunication;using hslcommunication.enthernet;

Start Program

First create the three projects, the server project, the client project, the common project, then use NuGet to install both the client and server two projects, then switch to the server program, and the next step is to actually create the program.

    • Common project: A class that stores the common use of servers and clients.
    • Server Project: Message Routing Center. All messages sent by the client are forwarded by the server first.
    • Client projects: Clients interacting with the user, accepting input from the user and displaying it.

In the whole project, the core part is the network communication, need to implement the client to send messages to the server, this is relatively good implementation, because the server's IP address and port are public. But the client's IP and port are unknown because we want to implement any computer that can log on to the client. So we need to use hslcommunication to make these operations easy.

The Hslcommunication component needs to be installed on both the server side and client side. Because we want to implement communication on the client and server side, the communication function is numerous, so we need to make a contract, the ID of the message, we finally distinguish the message according to the ID of the message.

    • 1 system messages to show who who is online and who who has downline
    • 2 is the message sent by the user, which is displayed in the Chat window
    • 3 Client online information, so the information of the online client
    • 4 Force client offline, for the server to send the shutdown instructions to the client, the client received after the exit program.

In summary, this project has been initially formed, and through the message ID can be implemented by other functions of their own extension, you can achieve any interactive operation. Not necessarily a chat system, a variety of data synchronization mechanism, push mechanism, LAN mechanism of the game program can also be achieved.

The source code address of this project is as follows: Https://github.com/dathlin/NetChatRoom

Server

Fill in the core block first

        #region Core network services related to private netcomplexserver complexserver;                                             private void Complexserverinitialization () {complexserver = new netcomplexserver ();          Instantiate complexserver.keytoken = new Guid ("91625BAD-D581-44AB-B121-FFFF5BCB83FB");         Set token, enhance security complexserver.lognet = new HslCommunication.LogNet.LogNetSingle ("Log.txt");                           Set up logging, if not required, you can delete complexserver.clientonline + = Complexserver_clientonline;                         Trigger Complexserver.clientoffline + = Complexserver_clientoffline When the client is online;       The client triggers Complexserver.allclientsstatuschange + = complexserver_allclientsstatuschange when offline;                           As long as there are clients on-line or offline trigger complexserver.acceptstring + = complexserver_acceptstring;                                                   Complexserver.serverstart (12345) is triggered when a message is sent by the client; To start the service, you need to selectChoose a port} private void Complexserver_allclientsstatuschange (String object1) {} private void Complexserver_acceptstring (Asyncstateone object1, NetHandle object2, String object3) {/ /We require///1 is a system message,//2 is a message sent by user//3 client online Information//4 force client Offline//when your message A large number of head types can be specified in a unified class center if (object2 = = 2) {//messages from the client, there is only one such situation Netm Essage msg = new Netmessage () {fromname = Object1. Loginalias, time = DateTime.Now, Type = "string", Content = Objec                T3,}; Mass out complexserver.sendallclients (2, Jobject.fromobject (msg).            ToString ()); }} private void Complexserver_clientoffline (Asyncstateone object1, String object2) {//Guest To send messages to the client Complexserver.sendAllclients (1, Object1. IpAddress + "" + Object1.            Loginalias + ":" + object2); Send online information complexserver.sendallclients (3, Removeonline (Object1.            Clientuniqueid)); Displays information ShowMsg (OBJECT1) in the main interface. IpAddress + "" + Object1.            Loginalias + ":" + object2);        Showonlineclient (); } private void Complexserver_clientonline (Asyncstateone object1) {//Client on-line, send message to client C Omplexserver.sendallclients (1, Object1. IpAddress + "" + Object1.            Loginalias + ": On-line"); Send online information netaccount account = new Netaccount () {Guid = Object1. Clientuniqueid, Ip = Object1. IpAddress, Name = Object1.            Loginalias, Onlinetime = DateTime.Now.ToString (),};            Complexserver.sendallclients (3, Addonline (account)); Displays information ShowMsg (OBJECT1) in the main interface. IpAddress + "" + Object1.            Loginalias + ": On-line"); ShowonlineClient (); } #endregion

  Here is a feature that implements information logging for online clients, contains a lot of information, and can be extended

        #region Online Client information implementation block Private list<netaccount> all_accounts = new list<netaccount> ();        Private Object Obj_lock = new Object (); Add a user account to the online client private string Addonline (Netaccount Item) {string result = string.            Empty; Lock (Obj_lock) {all_accounts.                ADD (item); result = Jarray.fromobject (all_accounts).            ToString ();        } return result; }//Remove the online account and return the appropriate online information private string Removeonline (String guid) {string result = string.            Empty; Lock (Obj_lock) {for (int i = 0; i < all_accounts. Count; i++) {if (All_accounts[i]. GUID = = GUID) {all_accounts.                        RemoveAt (i);                    Break }} result = Jarray.fromobject (all_accounts).            ToString ();          }  return result; } #endregion

About the class of online information

    <summary>///    Extended account information, record unique tag, IP address, online time, name////    </summary> public    class Netaccount    {//<summary>///Unique ID///        </summary> public        string Guid {get; set;}        <summary>////IP address///        </summary> public        string IP {get; set;}        <summary>///Online Time///        </summary> public        string Onlinetime {get; set;}        <summary>/////        </summary> Public        string name {get; set;}        <summary>///String identification Form///</summary>//        <returns></returns>        public override string ToString ()        {            return "[" + Ip + "]:" + Name;        }    }

The following shows how to send a system message to all clients on the server side

        private void Userbutton1_click (object sender, EventArgs e)        {            //server sends system messages to client            if (!string. IsNullOrEmpty (TextBox2.Text))            {                //messages from the client, there is only one such situation                netmessage msg = new Netmessage ()                {                    FromName = "System", Time                    = DateTime.Now,                    Type = "string",                    Content = TextBox2.Text,                };                Mass out                complexserver.sendallclients (2, Jobject.fromobject (msg). ToString ());            }        }

This enables the message to be sent.

Client

Fill in the core block first

       #region Client Network block private netcomplexclient net_socket_client = new Netcomplexclient (); private void Net_socket_client_initialization () {try {net_socket_client.          Keytoken = new Guid ("91625BAD-D581-44AB-B121-FFFF5BCB83FB"); The token must be set net_socket_client consistent with the server token of the connection.                                     Endpointserver = new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("127.0.0.1"), 12345); The address of the connected server must correspond to the server-side information net_socket_client.                                              Clientalias = LoginName; Incoming account name Net_socket_client.                       Acceptstring + = net_socket_client_acceptstring; Net_socket_client is triggered when a string message is received.            Clientstart ();            } catch (Exception ex) {softbasic.showexceptionmessage (ex); }}///<summary>///Receive callback method for byte data of the server///</summary>//<param name= "state" > Network Connection object </param>//<param name= "Customer" > user-defined instruction header, with To differentiate data usage </param>///<param name= "Data" > Statistics </param> private void Net_socket_client_acceptstr  ING (asyncstateone State, NetHandle Customer, String data) {//We specify//1 is a system message,// 2 is the message sent by the user//3 client Online//4 exit instruction//When you have a lot of message headers, you can make a provision in a unified Class center if (custome            r = = 1) {showsystemmsg (data);            } else if (customer = = 2) {showmsg (data);            } else if (customer = = 3) {showonlineclient (data);            } else if (customer = = 4) {//exit system Quitsystem (); }} #endregion

When the user enters the sending message, it calls the following method:

        Send Message        private void Userbutton1_click (object sender, EventArgs e)        {            if (string. IsNullOrEmpty (TextBox3.Text)) return;            Net_socket_client. Send (2, textbox3.text);            Textbox3.clear ();        }

The specific code logic also needs to refer to the source code on GitHub.

C # Asynchronous Communication network chat program development LAN Chat room development

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.