Common. UdpLib

Source: Internet
Author: User

Using system;
Using system. text;
Using system. collections;
Using system. Collections. Generic;
Using system. net;
Using system. net. Sockets;
Using system. Threading;
Using system. runtime. interopservices;
Using system. IO;

Namespace common. udplib
{
Public class _ bgz_udpstate
{
Public ipendpoint _ udpclientaddress = new ipendpoint (IPaddress. Any, 0 );
Public byte [] _ buffer = new byte [0];

Public _ bgz_udpstate ()
{
_ UdpClientAddress = new IPEndPoint (IPAddress. Any, 0 );
_ Buffer = new byte [0];
}

Public string StrUpdClientAddress
{
Get
{
Return _ UdpClientAddress. Address. ToString () + ":" + _ UdpClientAddress. Port. ToString ();
}
}
}
}

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

Namespace Common. UdpLib
{

Public enum ErrorType {MaxConnect, Catch, DisConnect, DisAccept };

// Udp
Public delegate void _ Bgz_OnUdpBindEventDelegate (_ Bgz_UdpState state );
Public delegate void _ Bgz_OnUdpErrorEventDelegate (ErrorType errortype, string errormsg, _ Bgz_UdpState state );
Public delegate void _ Bgz_OnUdpReceiveEventDelegate (_ Bgz_UdpState state );
}

Using System;
Using System. Text;
Using System. Collections;
Using System. Collections. Generic;
Using System. Net;
Using System. Net. Sockets;
Using System. Threading;
Using System. Runtime. InteropServices;
Using System. IO;

Namespace Common. UdpLib
{
Public class UdpSocket
{
Private UdpClient _ listener = new UdpClient ();
Private int _ port = 0;
Private bool _ debug;
Private Thread _ thread;

Private struct ClientInfo
{
Public string IpAddress;
Public int Port;
Public clientinfo (string IPaddress, int port)
{
This. IPaddress = IPaddress;
This. Port = port;
}

Public clientinfo (ipendpoint IP)
{
This. IPaddress = IP. Address. tostring ();
This. Port = ip. Port;
}

Public string ClientID
{
Get
{
Return IpAddress + ":" + Port. ToString ();
}
}

Public IPEndPoint GetIPEndPoint (string IpAddress, int Port)
{
Try
{
IPAddress ip = Dns. GetHostEntry (IpAddress). AddressList [0];
Return new IPEndPoint (ip, Port );
}
Catch
{
Return new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 0 );
}
}

Public IPEndPoint
{
Get
{
Return GetIPEndPoint (this. IpAddress, this. Port );
}
}

}

Private List <ClientInfo> _ clientInfo;
# Region define delegates
/// <Summary>
/// Post-event after server binding
/// </Summary>
Public _ bgz_onudpbindeventdelegate fonbindeventdelegate;

/// <Summary>
/// Receives the post-processing event of client data
/// </Summary>
Public _ bgz_onudpreceiveeventdelegate fonreceiveeventdelegate;
/// <Summary>
/// Handle error messages
/// </Summary>
Public _ bgz_onudperroreventdelegate fonerroreventdelegate;
# Endregion

# Region event
Private void OnBindEvent (_ Bgz_UdpState state)
{
If (FOnBindEventDelegate! = Null) FOnBindEventDelegate (state );
}
Private void OnReceiveEvent (_ Bgz_UdpState state)
{
If (FOnReceiveEventDelegate! = Null) FOnReceiveEventDelegate (state );
}
Private void OnErrorEvent (ErrorType errortype, string msg, _ Bgz_UdpState state)
{
If (FOnErrorEventDelegate! = Null) FOnErrorEventDelegate (errortype, msg, state );
}
# Endregion

# Region Constructor and Destructor
Public UdpSocket ()
{
}

Public UdpSocket (int port)
{
_ Port = port;
}

~ UdpSocket ()
{
Stop ();
}
# Endregion

# Region private methods

Private void receive ()
{
Try
{
_ Bgz_udpstate STX = new _ bgz_udpstate ();
While (true)
{
Stx. _ Buffer = new byte [0];
Stx. _ UdpClientAddress = new IPEndPoint (IPAddress. Any, _ port );

Stx. _ Buffer = _ listener. Receive (ref stx. _ UdpClientAddress );

ClientInfo ci = new ClientInfo (stx. _ UdpClientAddress. Address. ToString (), _ port );
If (! _ ClientInfo. Contains (ci ))
{
_ ClientInfo. Add (ci );
}

OnReceiveEvent (stx );
}
}
Catch (Exception ex)
{
If (Debug)
{
OnErrorEvent (ErrorType. Catch, "cancecallback.2 Error! [Message]: \ r \ n "+ ex. Message +" [StackTrace]: \ r \ n "+ ex. StackTrace +" \ r \ n ", null );
}
}
}

# Endregion

# Region Public Methods

Public void Start ()
{
Try
{
_ Listener = new UdpClient (_ port );
_ Bgz_UdpState stx = new _ Bgz_UdpState ();
Stx. _ Buffer = new byte [0];
STX. _ udpclientaddress = new ipendpoint (IPaddress. Any, _ port );

Onbindevent (STX );
_ Clientinfo = new list <clientinfo> (100 );

_ Thread = new thread (New threadstart (receive ));
_ Thread. Name = "udpserver listener ";
_ Thread. Start ();
}
Catch (exception ex)
{
If (Debug)
{
Onerrorevent (errortype. Catch, "Start error! [Message]: \ r \ n "+ ex. Message +" [stacktrace]: \ r \ n "+ ex. stacktrace +" \ r \ n ", null );
}
}
}

Public void Stop ()
{
Try
{
_ ClientInfo. Clear ();

This. _ listener. Close ();

If (this. _ thread. IsAlive)
{
This. _ thread. Abort ();
}
}
Catch (Exception ex)
{
If (Debug)
{
OnErrorEvent (ErrorType. Catch, "Send Error! [Message]: \ r \ n "+ ex. Message +" [StackTrace]: \ r \ n "+ ex. StackTrace +" \ r \ n ", null );
}
}
}

Public void Send (string hostname, int port, byte [] msg)
{
Try
{
IPAddress ip = Dns. GetHostEntry (hostname). AddressList [0];
_ Listener. Send (msg, msg. Length, new IPEndPoint (ip, port ));
}
Catch (Exception ex)
{
If (Debug)
{
OnErrorEvent (ErrorType. Catch, "Send Error! [Message]: \ r \ n "+ ex. Message +" [StackTrace]: \ r \ n "+ ex. StackTrace +" \ r \ n ", null );
}
}
}

Public void Send (IPEndPoint ip, byte [] msg)
{
Try
{
_ Listener. Send (msg, msg. Length, ip );
}
Catch (exception ex)
{
If (Debug)
{
Onerrorevent (errortype. Catch, "Send error! [Message]: \ r \ n "+ ex. Message +" [stacktrace]: \ r \ n "+ ex. stacktrace +" \ r \ n ", null );
}
}
}

Public void Send (byte [] msg)
{
Foreach (ClientInfo c in _ clientInfo)
{
Send (c. IPEndPoint, msg );
}
}

# Endregion

# Region property

Public bool Debug
{
Get
{
Return _ debug;
}
Set
{
_ Debug = value;
}
}
 
# Endregion
}
}

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.