//Server Binding
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 2015);
serverSocket.Bind(ipEndPoint);
//Begin Recceive from any client
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
EndPoint epSender = (EndPoint)ipeSender;
serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnNetworkBytesReceived), epSender);
private void OnNetworkBytesReceived(IAsyncResult ar)
{
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
EndPoint epSender = (EndPoint)ipeSender;
int BytesRead = serverSocket.EndReceiveFrom(ar, ref epSender);
//parse your data
ParseNetworkBytes(BytesRead, epSender);
serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnNetworkBytesReceived), epSender);
}//OnNetworkBytesReceived()
//for sending to client
Byte[] byteDataTemp = msg.messagePacketByLength(i, Constants.MAXSENDBUFFERSIZE);
serverSocket.BeginSendTo(byteDataTemp, 0, byteDataTemp.Length, SocketFlags.None, epRcvr, new AsyncCallback(OnSend), null);
private void OnSend(IAsyncResult ar)
{
try
{
lock (serverSocket)
{
serverSocket.EndSendTo(ar);
}
}
catch (ObjectDisposedException objexp)
{
}
catch (Exception exp)
{
}
}//OnSend()