2011-11-25 12 views
5

मुझे यूडीपी क्लाइंट/सर्वर कनेक्शन के लिए एमएसडीएन पर यह महान कोड मिला, हालांकि ग्राहक केवल सर्वर को भेज सकता है, यह वापस जवाब नहीं दे सकता है। मैं इसे कैसे बना सकता हूं ताकि सर्वर उस क्लाइंट को जवाब दे सके जो संदेश भेजता है। सर्वरयूडीपी श्रोता ग्राहक को जवाब देता है

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

यह वही कोड है, केवल उलट भूमिकाओं के साथ। ग्राहक को कुछ बंदरगाहों पर सुनने की ज़रूरत है, और सर्वर प्रसारण पते के बजाय ग्राहक के अंत बिंदु पर संदेश भेजता है।

संबंधित मुद्दे