Note that there are some explanatory texts on larger screens.

plurals
  1. POThread to receive data from an ip and port
    primarykey
    data
    text
    <p>I would like to write a program to receive some data using tcpClient from a specified ip and port number. First time I did it using while(true). Friend of mine told me to use thread instead of while loop. So I did as he said.</p> <pre><code>public static void receiveThread() { TcpClient tcpClient = new TcpClient(); try { tcpClient.Connect(ipAddress, incPort); Console.WriteLine("Connection accepted ..."); } catch (Exception e) { Console.WriteLine(e + "\nPress enter to exit..."); Console.ReadKey(); return; } NetworkStream stream = tcpClient.GetStream(); StreamReader incStreamReader = new StreamReader(stream); try { data = incStreamReader.ReadLine(); Console.WriteLine("Received data: {0}", data); } catch (Exception e) { Console.WriteLine(e + "\nPress enter to exit..."); } } </code></pre> <p>Works fine but not as good as I would like it to work. When Im running my program and sending to it for exaple "Hello world" string, it receives it and then finishing the job and exiting. I want to keep the thread up for more incoming data but I do not know how to do it. Maybe someone has a clue for me how to do it ?</p> <p>To sending data Im using this</p> <pre><code>using System; using System.Net; using System.Net.Sockets; using System.IO; public class Program { public static string ipAddress = "127.0.0.1"; public static int listenerPort = 6600; public static string message; static void Main(string[] args) { TcpListener tcpListener = new TcpListener(IPAddress.Parse(ipAddress),listenerPort); tcpListener.Start(); Socket socket = tcpListener.AcceptSocket(); Console.WriteLine("Connection accepted..."); while (true) { if (socket.Connected) { NetworkStream networkStream = new NetworkStream(socket); StreamWriter streamWriter = new StreamWriter(networkStream); message = Console.ReadLine(); streamWriter.WriteLine(message); streamWriter.Flush(); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload