C # create a UDP server and receive client data

Source: Internet
Author: User

C # create a UDP server and receive client data




Server 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 {////// UDP Server Object ///Public class UDPServerClass {public delegate void MessageHandler (string Message); // defines the delegate event public event MessageHandler MessageArrived; public UDPServerClass () {// obtain the available IP address of the Local Machine IPAddress [] ips = Dns. getHostAddresses (Dns. getHostName (); foreach (IPAddress ipa in ips) {if (ipa. addressFamily = AddressFamily. interNetwork) {MyIPAddress = ipa; // obtain the local IP address break;} Note_StringBuilder = new StringBuilder (); PortName = 8080;} public UdpClient ReceiveUdpClient ;////// Listener port name ///Public int PortName ;////// Local address ///Public IPEndPoint LocalIPEndPoint ;////// Log records ///Public StringBuilder Note_StringBuilder ;////// Local IP address ///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 ();}////// Receive data ///Private void ReceiveData () {IPEndPoint local = new IPEndPoint (MyIPAddress, PortName); ReceiveUdpClient = new UdpClient (local); IPEndPoint remote = new IPEndPoint (IPAddress. any, 0); while (true) {try {// when you close udpClient, this statement will generate an exception byte [] receiveBytes = ReceiveUdpClient. receive (ref remote); string receiveMessage = Encoding. default. getString (receiveBytes, 0, receiveBytes. length); // receiveMessage = ASCII Encoding. 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 ;}}}////// Add log information to Note_StringBuilder ///Public void AddMessage_Note_StringBuilder (){}}}


Simple interface 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 UDPServerForm : 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.Environment.Exit(System.Environment.ExitCode);        }    }}









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.