views:

108

answers:

2

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();
        }
    }
}
+1  A: 

Your friend had you use a thread so your main application wasn't locked up. Now that you've created a new thread you can use a while loop inside that thread like you were doing previously.

William
Right, thanks for your answer.
Allek
+2  A: 

Hello!

Have a look at this property of the TCPClient Object

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.connected.aspx

you can use it as such

while(tcpClient.Connected)
{
    // do something while conn is open
}
Tony
Thank you, you were really helpfull, cheers.
Allek