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.
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...");
}
}
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 ?
To sending data Im using this
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();
}
}
}