Muzammil Rajpoot

Muzammil Rajpoot

  • NA
  • 18
  • 4.9k

Tcplistener/client application

Jan 3 2020 5:51 PM
hello everyone,
 
I am trying to make 2 different applications on 2 different computers respectively. Moreover i want these applications to communicate over ethernet cable.
 
The code for receiver application is guven below and unfortunately it is not working. Instead i am getting some error i.e.
 
"The requested address is not valid in its context"
 
Making improvements in this code will be prefered instead of links to other sites.
  1. public sealed partial class MainPage : Page  
  2. {  
  3. public MainPage()  
  4. {  
  5. this.InitializeComponent();  
  6. }  
  7. TcpListener Listener;  
  8. IPAddress localAddr = IPAddress.Parse("192.168.x.xx");  
  9. Int32 port = Int32.Parse("5001");  
  10. private void Recieve_Click(object sender, RoutedEventArgs e)  
  11. {  
  12. Listener = new TcpListener(localAddr,port);  
  13. Listener.Start();  
  14. Byte[] bytes = new Byte[256];  
  15. String data = null;  
  16. while (true)  
  17. {  
  18. IP.Text = "Waiting for a connection... ";  
  19. // Perform a blocking call to accept requests.  
  20. // You could also user server.AcceptSocket() here.  
  21. TcpClient client = Listener.AcceptTcpClient();  
  22. IP.Text = "Connected!";  
  23. // Get a stream object for reading and writing  
  24. NetworkStream stream = client.GetStream();  
  25. int i;  
  26. // Loop to receive all the data sent by the client.  
  27. while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)  
  28. {  
  29. // Translate data bytes to a ASCII string.  
  30. data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);  
  31. IP.Text = data;  
  32. // Process the data sent by the client.  
  33. data = data.ToUpper();  
  34. byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);  
  35. // Send back a response.  
  36. stream.Write(msg, 0, msg.Length);  
  37. // IP.Text = "Sent: {0}";  
  38. }  
  39. // Shutdown and end connection  
  40. client.Close();  
  41. }  
  42. }  
  43. }  
  44. }  

Answers (1)