简体   繁体   English

在C#中接收和发送数据

[英]Receiving and sending data in C#

I'm 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. 我有一个程序,我用它来发送字符串使用tcpClient到一个程序,我在其中侦听指定的端口。 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. 看起来send方法可能有问题。 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...

Several problems here: 这里有几个问题:

  1. StreamReader has a 4kB buffer and will try to read as much as possible in the first call to ReadLine() . StreamReader有一个4kB的缓冲区,在第一次调用ReadLine()会尝试尽可能多地读取。 The result is that you might have data in the StreamReader and go into Poll() when there's no more data available because it's already been read. 结果是您可能在StreamReader中有数据,并且当没有更多可用数据时进入Poll(),因为它已被读取。
  2. Poll() takes microseconds. Poll()需要几微秒。 Waiting 0.02ms for incoming data is likely to return false unless the data is there before you call Poll() . 等待0.02ms的传入数据很可能会返回false,除非在调用Poll()之前存在数据。
  3. You create a new StreamReader on every iteration, which might discard data already read in the previous one. 您可以在每次迭代时创建一个新的StreamReader,这可能会丢弃先前已读取的数据。

If you're just going to read lines and want a timeout and a StreamReader , I would do something like: 如果您只是想读取行并想要超时和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);
        } 
    }
}

Ensure that the data actually exists on the stream before chasing ghosts. 在追逐鬼魂之前,确保数据实际存在于流上。 If there is ALWAYS data we can approach the problem, however looking at it logically it appears as though the stream is either being nulled out or there is just no data on it. 如果有ALWAYS数据我们可以解决问题,但是从逻辑上看它看起来好像流被淘汰或者它上面没有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM