1
我希望對此問題提供任何幫助/反饋。我正在C#中開發一個異步套接字連接,我想設置一個廣播客戶端接收器,使其廣播本地網絡服務器,然後它從本地服務器接收消息。主要問題是首先我想從一個客戶端向不同的服務器進行廣播,然後從所有服務器中檢索IP地址。這裏是客戶端代碼的一部分。也服務器端工作正常。異步客戶端廣播接收器
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);
}
}
你見過這個網站通過'http:// meta.codereview.stackexchange.com /'? –