Im still trying to improve a little bit what I wrote before. Now I faced a problem with receiving data. I have a program which I use to send string using tcpClient to a program in which Im listening on a specified port. It works fine so I decided to send data forward one more time
public static void receiveThread()
{
while (true)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
Console.WriteLine("Waiting for connection...");
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Console.WriteLine("Connected with {0}", tcpClient.Client.RemoteEndPoint);
while (!(tcpClient.Client.Poll(20, SelectMode.SelectRead)))
{
NetworkStream networkStream = tcpClient.GetStream();
StreamReader streamReader = new StreamReader(networkStream);
data = streamReader.ReadLine();
if (data != null)
{
Console.WriteLine("Received data: {0}", data);
send(data); // Here Im using send Method
}
}
Console.WriteLine("Dissconnected...\n");
tcpListener.Stop();
}
}
/// <summary>
/// Sending data
/// </summary>
/// <param name="data">Data to send</param>
public static void send(string data)
{
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect(ipAddress, sendPort);
Console.WriteLine("Connected with {0}", tcpClient.Client.RemoteEndPoint);
}
catch (Exception e)
{
Console.WriteLine(e);
}
if (tcpClient.Connected)
{
NetworkStream networkStream = tcpClient.GetStream();
StreamWriter streamWriter = new StreamWriter(networkStream);
Console.WriteLine("Messege {0} to {1}", data, tcpClient.Client.RemoteEndPoint);
streamWriter.WriteLine(data);
streamWriter.Flush();
tcpClient.Close();
}
}
Sometimes it works fine, but more often, lets call it a receiver, can't get what Im trying to send. And I really do not konw what is wrong with it. Looks like there can be a problem with send method. Here is an example of receivers output
Waiting for connection...
Connected with 127.0.0.1:52449
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52450
Received data: qweqwe
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52451
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52452
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52453
Received data: zxczx
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52454
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52455
Received data: aasd
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52457
Received data: www
Dissconnected...