2011-11-25 2 views
5

UDP 클라이언트/서버 연결에 대해 MSDN에서이 훌륭한 코드를 발견했지만 클라이언트는 서버로만 보낼 수 있습니다. 응답이 없습니다. 서버가 메시지를 보내는 클라이언트에 응답 할 수 있도록 어떻게 만들 수 있습니까? [서버UDP Listener가 클라이언트에 응답했습니다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 
using System.IO; 
using System.Security.Cryptography; 


namespace UDP_Server 
{ 
    class Program 
    { 
     private const int listenPort = 11000; 

     private static void StartListener() 
     { 
      bool done = false; 

      UdpClient listener = new UdpClient(listenPort); 
      IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); 
      try 
      { 
       while (!done) 
       { 
        Console.WriteLine("Waiting for broadcast"); 
        byte[] bytes = listener.Receive(ref groupEP); 
        Console.WriteLine("Received broadcast from {0} :\n {1}\n",groupEP.ToString(), Encoding.ASCII.GetString(bytes, 0, bytes.Length)); 
       } 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e.ToString()); 
      } 
      finally 
      { 
       listener.Close(); 
      } 
     } 

     public static int Main() 
     { 
      StartListener(); 

      return 0; 
     } 
    } 

} 

그리고 클라이언트

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 
using System.IO; 
using System.Security.Cryptography; 

namespace UDP_Client 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Send("TEST STRING"); 
      Console.Read(); 
     } 
     static void Send(string Message) 
     { 
      Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
      IPAddress broadcast = IPAddress.Parse("10.1.10.117"); 
      byte[] sendbuf = Encoding.ASCII.GetBytes(Message); 
      IPEndPoint ep = new IPEndPoint(broadcast, 11000); 
      s.SendTo(sendbuf, ep); 
     } 
    } 
} 

답변

8

그냥 그것을 라운드 다른 방법을한다. 클라이언트에서 StartListener으로 전화하면 서버와 같은 udp 데이터를 수신 할 수 있습니다.

서버에서 고객 코드로 데이터를 전송하십시오.

0

역순으로 동일한 코드입니다. 클라이언트는 일부 포트에서 수신 대기해야하며 서버는 브로드 캐스트 주소 대신 클라이언트의 엔드 포인트로 메시지를 전송합니다.

관련 문제