2010-04-17 2 views
0

를받을 수없는 것은 여기에 내 코드UDP는 데이터

내가 서버를 찾을 시도하는 코드 위에 사용
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
sck.Bind(new IPEndPoint(IPAddress.Any, 0)); 

// Broadcast to find server 
string msg = "Imlookingforaserver:" + udp_listen_port; 
byte[] sendBytes4 = Encoding.ASCII.GetBytes(msg); 
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("255.255.255.255"), server_port); 
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); 
sck.SendTo(sendBytes4, groupEP); 

//Wait response from server 
Socket sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
sck2.Bind(new IPEndPoint(IPAddress.Any, udp_listen_port)); 
byte[] buffer = new byte[128]; 
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, udp_listen_port); 
sck2.ReceiveFrom(buffer, ref remoteEndPoint); //<<< I never pass this line 

입니다. 먼저 메시지를 브로드 캐스트 한 다음 서버에서 응답을 기다립니다.

테스트 저는 C++로 작성되고 Windows Vista에서 실행되는 서버로 만들었습니다. C#으로 작성된 클라이언트는 서버와 동일한 시스템에서 실행됩니다.

문제점 : 서버는 클라이언트 브로드 캐스트 메시지를 수신 할 수 있지만 클라이언트는 서버로부터 아무 것도 수신 할 수 없습니다.

나는 C++로 클라이언트를 작성하려고하는데 매력처럼 작동한다. 내 문제는 C# 클라이언트에 있다고 생각한다.

+0

두 대의 컴퓨터에서 실행 해 보았습니까? –

답변

2

브로드 캐스트하기 전에 해당 포트에서 수신을 시작합니다. 당신은 당신의 패킷을 놓칠 수 있으므로 비 연결적인 UDP를 사용하고 있습니다.

Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
sck.Bind(new IPEndPoint(IPAddress.Any, 0)); 
//Wait response from server 
Socket sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
sck2.Bind(new IPEndPoint(IPAddress.Any, udp_listen_port)); 
byte[] buffer = new byte[128]; 
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, udp_listen_port); 

// Broadcast to find server 
string msg = "Imlookingforaserver:" + udp_listen_port; 
byte[] sendBytes4 = Encoding.ASCII.GetBytes(msg); 
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("255.255.255.255"), server_port); 
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); 
sck.SendTo(sendBytes4, groupEP); 


sck2.ReceiveFrom(buffer, ref remoteEndPoint);