I would appreciate any help/feedback on this issue. I'm developing an Asynchronous socket connection in C#, i would like to set a broadcast client receiver such that it broadcast local network servers and then it receives the messages from the local servers. the main issue is that first i want to broadcast to different servers from one client and then retrieve the ip addresses from all the servers. here is part of the client code. also the server side works fine.
public void ButtonConnectOnClick()
{
// Init socket Client
newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
newsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPAddress ipAddress = IPAddress.Broadcast; //Parse(txtServerIP.Text);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, BROADCASTPORT);
epServer = (EndPoint)ipEndPoint;
string tmp = "hello";
byteData = Encoding.ASCII.GetBytes(tmp);
newsock.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, epServer, new AsyncCallback(OnSend), null);
byteData = new byte[1024];
newsock.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null);
}
private void OnSend(IAsyncResult ar)
{
try
{
newsock.EndSend(ar);
}
catch (ObjectDisposedException)
{ }
catch (Exception ex)
{
MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void OnReceive(IAsyncResult ar)
{
try
{
newsock.EndReceive(ar);
byteData = new byte[1024];
//Start listening to receive more data from the user
newsock.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null);
}
catch (ObjectDisposedException)
{ }
catch (Exception ex)
{
MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}