【问题标题】:Thread to receive data from an ip and port从 ip 和端口接收数据的线程
【发布时间】:2009-11-27 02:33:04
【问题描述】:

我想编写一个程序来使用 tcpClient 从指定的 ip 和端口号接收一些数据。我第一次使用 while(true)。我的朋友告诉我使用线程而不是 while 循环。所以我就照他说的做了。

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...");
    }
}

工作正常,但不如我希望的那么好。当我运行我的程序并向它发送例如“Hello world”字符串时,它会接收它,然后完成工作并退出。我想保持线程以获取更多传入数据,但我不知道该怎么做。也许有人知道我该怎么做?

使用这个发送数据我

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();
        }
    }
}

【问题讨论】:

    标签: c# multithreading tcpclient


    【解决方案1】:

    看看 TCPClient 对象的这个属性

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

    你可以这样使用它

    while(tcpClient.Connected)
    {
        // do something while conn is open
    }
    

    【讨论】:

      【解决方案2】:

      您的朋友让您使用线程,这样您的主应用程序就不会被锁定。现在您已经创建了一个新线程,您可以像以前一样在该线程中使用 while 循环。

      【讨论】:

        猜你喜欢
        • 2011-03-19
        • 1970-01-01
        • 2019-04-14
        • 2013-06-28
        • 2013-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多