C # establishes a UDP server and receives client data

Source: Internet
Author: User




Server-Side object class Library:


Using system;using system.collections.generic;using system.linq;using system.text;using System.Net.Sockets;using System.net;using system.threading;using system.io;namespace udpchatexample{//<summary>//UDP server object//        </summary> public class Udpserverclass {public delegate void MessageHandler (string Message);//define Delegate Events        public event MessageHandler messagearrived; Public Udpserverclass () {//Get the native available IP address ipaddress[] ips = dns.gethostaddresses (dns.gethostname            ()); foreach (IPAddress IPA in IPs) {if (IPA.                    AddressFamily = = addressfamily.internetwork) {myipaddress = ipa;//get local IP address                Break            }} Note_stringbuilder = new StringBuilder ();        PortName = 8080;        } public UdpClient receiveudpclient; <summary>///Listening port name///</summary> PubLIC int portname;        <summary>///Local address///</summary> public ipendpoint localipendpoint;        <summary>///Log Records///</summary> public StringBuilder Note_stringbuilder;        <summary>///local IP address///</summary> public IPAddress myipaddress;            public void Thread_listen () {//Create a thread to receive the information sent from the remote host thread myThread = new Thread (receivedata);            Mythread.isbackground = true;        Mythread.start ();            }///<summary>///Receive data///</summary> private void Receivedata () {            IPEndPoint local = new IPEndPoint (myipaddress, portname);            Receiveudpclient = new UdpClient (local);            IPEndPoint remote = new IPEndPoint (ipaddress.any, 0);                  while (true) {try {//close udpclient This sentence produces an exception  byte[] Receivebytes = receiveudpclient.receive (ref remote);                    String receiveMessage = Encoding.Default.GetString (receivebytes, 0, receivebytes.length);                    ReceiveMessage = ASCIIEncoding.ASCII.GetString (receivebytes, 0, receivebytes.length); Messagearrived (String.                    Format ("{0} from {1}:{2}", DateTime.Now.ToString (), remote, receiveMessage));                    Try//{//byte[] sendbytes = Encoding.ASCII.GetBytes ("Is anybody there?");                    Receiveudpclient.send (Sendbytes, sendbytes.length, local);                }//catch (Exception e)//{//}//break;                } catch {break;        }}}///<summary>//Add log information to Note_stringbuilder///</summary> public void Addmessage_notE_stringbuilder () {}}} 


Interface Simple 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;namespace udpchatexample{public partial class UDPServe        Rform:form {public udpserverform () {InitializeComponent ();        } public delegate void Delegatechangetext (string Messages); void Changetxt (String Messages) {string sbtext = SB.            ToString (); SB. Remove (0, SB.)            Length); SB.            Append (Messages + "\ r \ n" + sbtext); richTextBox1.Text = SB.        ToString ();        } StringBuilder SB = new StringBuilder ();        private void Udpserverform_load (object sender, EventArgs e) {} Udpserverclass UDPServerClass1;            private void Button1_Click (object sender, EventArgs e) {UDPServerClass1 = new Udpserverclass ();            Udpserverclass1.thread_listen (); Udpserverclass1.messagearrived + = new Udpserverclass.messagehandler (udpserverclass1_messagearrived); } void Udpserverclass1_messagearrived (String Message) {RichTextBox1.        Invoke (New Delegatechangetext (Changetxt), Message); private void Udpserverform_formclosing (object sender, FormClosingEventArgs e) {System.environ ment.        Exit (System.Environment.ExitCode); }    }}









C # establishes a UDP server and receives client data

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.