C#socket TCP Communication Test & delegate value to control &directsound recording test source code

Source: Internet
Author: User
Tags dotnet

C # Inside the socket has asynchronous and synchronous points, can refer to: Https://docs.microsoft.com/en-us/dotnet/framework/network-programming/socket-code-examples to learn. Many examples of DirectSound socket sound collection on the network, but are a separate tool class (such as: Directsoundcapture), took a bit of time to implement the socket call, by the way sum up share. The following illustration is a test example:


Socket Client

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.Threading.Tasks; <summary>///Reference: https://docs.microsoft.com/en-us/dotnet/framework/network-programming/ Socket-code-examples///</summary> namespace Directsoundtest {class Socketclient {///<summary
            >///Start Client socket connection///</summary> public static void Startclient (string data) {  
            Data buffer for incoming data.

            byte[] bytes = new byte[1024];  
            Connect to a remote device.  
                try {//Establish the remote endpoint for the socket.  
                This is example uses port 11000 on the local computer.
                Iphostentry iphostinfo = Dns.gethostentry (Dns.gethostname ());
                IPAddress ipaddress = iphostinfo.addresslist[0]; IPEndPoint remoteEP = new IPENDPOInt (ipaddress, 11000);  
                Create a TCP/IP socket.

                Socket sender = new socket (ipaddress.addressfamily,sockettype.stream, protocoltype.tcp); Connect the socket to the remote endpoint.  
                Catch any errors. try {sender.

                    Connect (remoteEP); Console.WriteLine ("Socket connected to {0}", sender.)

                    Remoteendpoint.tostring ());  
                    Encode the data string into a byte array.

                    byte[] msg = Encoding.UTF8.GetBytes (data+ "<EOF>");  
                    Send the data through the socket. int bytessent = sender.

                    Send (msg);  
                    Receive the response from the remote device. int Bytesrec = sender.
                    Receive (bytes);

               Console.WriteLine ("echoed Test = {0}", Encoding.UTF8.GetString (bytes, 0, Bytesrec));     Release the socket. Sender.
                    Shutdown (Socketshutdown.both); Sender.

                Close (); The catch (ArgumentNullException ane) {Console.WriteLine ("Argumentnulle Xception: {0} ", ane.
                ToString ()); catch (SocketException se) {Console.WriteLine ("SocketException: {0 } ", SE.
                ToString ()); catch (Exception e) {Console.WriteLine ("unexpected Exception: {0}"
                , e.tostring ());
            The catch (Exception e) {Console.WriteLine (e.tostring ());
 }
        }

    }
}


Socket Service Side

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.Threading.Tasks; <summary>///Reference: https://docs.microsoft.com/en-us/dotnet/framework/network-programming/ Socket-code-examples///</summary> namespace Directsoundtest {class Socketserver {//Incoming DAT  
        A from the client.

        public static string data = NULL;
        <summary>///Boot service Socket listener///</summary> public static void Startlistening ()  
            {//Data buffer for incoming data.

            byte[] bytes = new byte[1024];  
            Establish the local endpoint for the socket.  
            Dns.gethostname returns the name of the The//host running the application.
            Iphostentry iphostinfo = Dns.gethostentry (Dns.gethostname ());
            IPAddress ipaddress = iphostinfo.addresslist[0]; IPEndPoint LocAlendpoint = new IPEndPoint (ipaddress, 11000);  
            Create a TCP/IP socket.

            Socket listener = new socket (ipaddress.addressfamily,sockettype.stream, protocoltype.tcp);  
            Bind the socket to the local endpoint and//listen for incoming connections. try {Listener.
                Bind (Localendpoint); Listener.

                Listen (10);  
                Start listening for connections.
                    while (true) {Console.WriteLine ("Waiting for a Connection ...");  
                    Program was suspended while waiting for a incoming connection. Socket handler = listener.
                    Accept ();

                    data = null;  
                    An incoming connection needs is processed.
                        while (true) {bytes = new byte[1024]; int Bytesrec = handler. Receive (bytes);
                        Data + + Encoding.UTF8.GetString (bytes, 0, Bytesrec); if (data.
                        IndexOf ("<EOF>") >-1) {break;  
                    }//Show the data on the console.

                    Console.WriteLine ("Text Received: {0}", data);  
                    Echo the data back to the client.

                    byte[] msg = Encoding.UTF8.GetBytes (data); Handler.
                    Send (msg); Handler.
                    Shutdown (Socketshutdown.both); Handler.
                Close ();
            The catch (Exception e) {Console.WriteLine (e.tostring ());
            } Console.WriteLine ("\npress ENTER to continue ...");

        Console.read ();
 }

    }
}


form & Delegate Pass values

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Threading;
Using System.Threading.Tasks;


Using System.Windows.Forms; Namespace Directsoundtest {    public partial class Frmsocket:form     {      &NBSP ; Public Frmsocket ()         {            InitializeComponent ();   & nbsp    }        ///<summary>        ///boot service socket connection   &NB Sp     ///</summary>        ///<param name= "sender" ></param>        ///<param name= "E" ></param>         private void Btnbindsocketserver_click (object sender, EventArgs e)         {            BTNBINDSOCKETSERVER.E
nabled = false;            thread thread = new Thread (() => {           
    socketserver.startlistening ();
           });             thread.
IsBackground = true;             thread.


Start ();        }        //Delegate setting value         delegate void Setdatatol
Istview (string data);         private void Setlistviewdata (string data)         {      & nbsp     if (this.listViewData.InvokeRequired)             {      &NBSP ;
        Setdatatolistview STCB = new Setdatatolistview (setlistviewdata);                 this.
Invoke (STCB, new object[] {data});            }       &NBSP;     Else             {                THI


S.listviewdata.items.add (data);                     {       ///<summary&gt
;        ///client send socket connection data        ///</summary>       &NBS P
<param name= "Sender" ></param>        ///<param name= "E" ></param>         private void Btnsocketclient_click (object sender, EventArgs e)         {& nbsp          //Send UTF8 text             byte[] buffer = Encoding.UTF8.Get
Bytes (This.textBox.Text.ToString ());
            String data = Encoding.UTF8.GetString (buffer);             thread thread = new Thread (() => {      &nbsp
        socketclient.startclient (data);                 setlistviewdata (data)//delegate set control value         &NBSP ;
 });             thread.
IsBackground = true;             thread.


Start ();        }        ///<summary>        ///Open Server &nbs P       ///</summary>        ///<param name= "Sender" ></param>        ///<param name= "E" ></param>         private void ToolStripMenuItems Erver_click (object sender, EventArgs e)         {            if (!)  setting.server_binded)             {               
Frmserver frmserver = new Frmserver ();                frmserver.show ();
                setting.server_binded = true;                         else {        & nbsp
      MessageBox.Show ("service-side registered");                     {       ///<summary&gt
;        ///open client        ///</summary>        /// ;p Aram Name= "sender" ></param>        ///<param name= "E" ></param>  
      private void Toolstripmenuitemclient_click (object sender, EventArgs e)         {
            frmclient frmclient = new Frmclient ();
            frmclient.show ();
        }    }}

delegate Writing-implements ListView control values that are modified across threads:

The delegate setting value

        delegate void Setdatatolistview (string data);
        private void Setlistviewdata (string data)
        {
            if (this.listViewData.InvokeRequired)
            {
                Setdatatolistview STCB = new Setdatatolistview (setlistviewdata);
                This. Invoke (STCB, new object[] {data});
            else
            {
                this.listViewData.Items.Add (data);

            }
        }

DirectSound Recording test source codeSocket examples and DirectSound recording codes are found on the GitHub.

GitHub Address: Https://github.com/BoonyaCSharp-ASP/DirectSoundTest


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.