【问题标题】:Receiving and sending data in C#在 C# 中接收和发送数据
【发布时间】:2010-12-22 15:35:44
【问题描述】:

我仍在努力改进我之前写的内容。 现在我遇到了接收数据的问题。我有一个程序,我用它使用 tcpClient 将字符串发送到我正在侦听指定端口的程序。它工作正常,所以我决定再发送一次数据

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

有时它可以正常工作,但更多时候,我们称它为接收器,但无法获取我试图发送的内容。我真的不知道它有什么问题。看起来发送方法可能有问题。这是接收器输出的示例

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...

【问题讨论】:

    标签: c# tcpclient tcplistener


    【解决方案1】:

    这里有几个问题:

    1. StreamReader 有一个 4kB 的缓冲区,并会在第一次调用 ReadLine() 时尝试尽可能多地读取。结果是您可能在 StreamReader 中有数据,并在没有更多可用数据时进入 Poll(),因为它已被读取。
    2. Poll() 需要几微秒。等待传入数据 0.02ms 可能会返回 false,除非在您调用 Poll() 之前数据已经存在。
    3. 您在每次迭代时都创建一个新的 StreamReader,这可能会丢弃前一个迭代中已读取的数据。

    如果您只是要阅读行并想要超时和StreamReader,我会这样做:

    delegate string ReadLineDelegate ();
    ...
    using (NetworkStream networkStream = tcpClient.GetStream()) {
        StreamReader reader = new StreamReader(networkStream);
        ReadLineDelegate rl = new ReadLineDelegate (reader.ReadLine);
        while (true) {
            IAsyncResult ares = rl.BeginInvoke (null, null);
            if (ares.AsyncWaitHandle.WaitOne (100) == false)
                break; // stop after waiting 100ms
            string str = rl.EndInvoke (ares);
            if (str != null) {
                Console.WriteLine ("Received: {0}", str);
                send (str);
            } 
        }
    }
    

    【讨论】:

    • 还不知道这里发生了什么。我不像我想的那样擅长它。你能解释一下吗?还有其他更好的选择来接收该数据并在不使用 StreamReader 的情况下将其发送出去吗?这是我第一次尝试写这样的东西,所以我不确定什么是更好或更坏
    • 上述代码所做的是读取行,直到从服务器端关闭流或直到读取一个需要超过 100 毫秒。至于读/写的其他选项,这取决于你想做什么。 “自然”接口是使用 byte [] 和 Socket。
    【解决方案2】:

    在追鬼之前确保数据确实存在于流中。如果总是有数据,我们可以解决问题,但是从逻辑上看,它看起来好像流要么被清空,要么上面没有数据。

    【讨论】:

    • 似乎这取决于数据传入的速度,而不是每个数据都可以发送,因此大部分数据都会丢失。你的回答让我更仔细地考虑了:>
    猜你喜欢
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多