C # Socket Asynchronous chat Room

Source: Internet
Author: User
Tags int size readline

Socket asynchronous communication, the thread pool is the system to maintain the threads

Note: When calling asynchronously, you cannot use the method called synchronously, and the thread blocks

Server:

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Net;

Using System.Net.Sockets;
        Namespace Socketdemo {class Clientinfo {public socket socket {get; set;}
        public bool IsOpen {get; set;}
    public string Address {get; set;} }//Manage client class Clientmanager {static list<clientinfo> clientlist = new List<clientinfo
        > (); public static void Add (Clientinfo info) {if (!) Isexist (info.
            Address)) {Clientlist.add (info); } public static bool Isexist (string address) {return clientlist.exists (item => s Tring. Compare (address, item.
        Address, true) = = 0);
                public static void Close (string address) {Clientlist.foreach (item => { if (string. Compare (address, item. Address, true) = = 0) {item. IsopEn = false;
        }
            });
            //Send message to clientlist public static void Sendmsgtoclientlist (String msg, string address = null) {
            byte[] bt = Encoding.UTF8.GetBytes (msg); Clientlist.foreach (item => {if (item). IsOpen && (address = NULL | | item. Address!=) {item. Socket.beginsend (BT, 0, Bt.) Length, Socketflags.none, New AsyncCallback (Sendtarget), item.
                Socket);
        }
            }); private static void Sendtarget (IAsyncResult res) {//socket client = (Socket) Res.
            asyncstate; int size = client.
        Endsend (RES);
        }///Receive Message class Receivehelper {public byte[] Bytes {get; set;} public void Receivetarget (IAsyncResult res) {Socket client = (socket) Res.
            asyncstate; int size = client.
            EndReceive (RES); IF (Size > 0) {string stringdata = Encoding.UTF8.GetString (Bytes, 0, size); String address = client. Remoteendpoint.tostring (); Gets the client's IP and port if (stringdata. IndexOf ("Exit") >-1) {Clientmanager.sendmsgtoclientlist (address + "Disconnected from server", addr
                    ESS);
                    Clientmanager.close (address);
                    Console.WriteLine (address + "disconnected from server");
                    Console.WriteLine (Address + "" + DateTimeOffset.Now.ToString ("G"));
                Return
                    else {Console.WriteLine (stringdata);
                    Console.WriteLine (Address + "" + DateTimeOffset.Now.ToString ("G"));
                Clientmanager.sendmsgtoclientlist (StringData, address); }//Continue waiting for client. BeginReceive (Bytes, 0, Bytes.length, Socketflags.none, new AsyncCallback (receIvetarget), client);

        }//Listener request class Accepthelper {public byte[] Bytes {get; set;} public void Accepttarget (IAsyncResult res) {Socket server = (socket) Res.
            asyncstate; Socket client = server.
            Endaccept (RES); String address = client.

            Remoteendpoint.tostring ();
            Clientmanager.add (New Clientinfo () {Socket = client, address = address, IsOpen = true}); Receivehelper rs = new Receivehelper () {Bytes = this.
            Bytes}; IAsyncResult recres = client. BeginReceive (Rs. Bytes, 0, Rs. Bytes.length, Socketflags.none, New AsyncCallback (Rs.
            Receivetarget), client); Continue to monitor the server.
        BeginAccept (New AsyncCallback (Accepttarget), server); } class Program {static void Main (string[] args) {Socket server = new Socket (
            AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Server. Bind (New IpendpoInt (Ipaddress.parse ("127.0.0.1"), 200)); Bind the ip+ port server. Listen (10);

            Start listening for Console.WriteLine ("Wait for connection ...");
            Accepthelper CA = new Accepthelper () {Bytes = new byte[2048]}; IAsyncResult res = server. BeginAccept (new AsyncCallback (CA).

            accepttarget), server); String str = string.
            Empty;
                while (str!= "exit") {str = Console.ReadLine ();
                Console.WriteLine ("ME:" + DateTimeOffset.Now.ToString ("G"));
            Clientmanager.sendmsgtoclientlist (str); } server.
        Close (); }
    }
}

Client:

Using System;
Using System.Text;
Using System.Net;

Using System.Net.Sockets;
        Namespace Consoleapplication {class Program {static byte[] inbytes = new byte[2048];
        Static byte[] Oubytes = new byte[2048]; static void Main (string[] args) {//Connect to server Socket client = new Socket (addressfamily.in
            Ternetwork, SocketType.Stream, protocoltype.tcp); Client.
            BeginConnect ("127.0.0.1", New AsyncCallback (Connecttarget), client); Receive input concurrency message string str = string.
            Empty;
                while (str!= "Exit") {Console.WriteLine ("ME:" + DateTimeOffset.Now.ToString ("G"));
                str = Console.ReadLine ();
                Inbytes = Encoding.UTF8.GetBytes (str); Client. BeginSend (inbytes, 0, Inbytes.
            Length, Socketflags.none, New AsyncCallback (Sendtarget), client); } client.
        Close (); } static void Connecttarget (IasyncResult res) {Socket client = (socket) Res.
            asyncstate; Client.
            EndConnect (RES); Client.
        BeginReceive (oubytes, 0, 2048, Socketflags.none, receivetarget, client); static void Sendtarget (IAsyncResult res) {//socket client = (Socket) Res.
            asyncstate; int size = client.
        Endsend (RES); static void Receivetarget (IAsyncResult res) {Socket client = (socket) Res.
            asyncstate; int size = client.
            EndReceive (RES);
                if (Size > 0) {Console.WriteLine (Encoding.UTF8.GetString (oubytes, 0, size)); Console.WriteLine (client.
            Remoteendpoint + "" + DateTimeOffset.Now.ToString ("G")); //Continue waiting for input client.
        BeginReceive (oubytes, 0, 2048, Socketflags.none, new AsyncCallback (Receivetarget), client);
 }
    }
}


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.