开发者

Thread to receive data from an ip and port

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 = 开发者_如何学JAVAnew StreamWriter(networkStream);

            message = Console.ReadLine();
            streamWriter.WriteLine(message);
            streamWriter.Flush();
        }
    }
}


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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜