Welcome to visit tcdos.com
...

by Zengjing 2020-05-26

TCP连接传输数据接收异常

业务场景

摄像头抓拍图片,对图片进行Base64位转码,通过TCP传输至目标用户,接收方偶尔出现异常,转码字符接收不完整,导致图片无法打印。

问题分析

经观察,图片尺寸大,进行Base64位转码后生成的字符长度大,TCP发生多次拆包传输后粘包不完整导致接收失败。

解决方案

每次接收时将线程等待10ms。

示例代码
tcp = new TcpListener(IPAddress.Any, port);
tcp.Start();
while (true)
{
    TcpClient client = null;
    NetworkStream ns = null;
    try
    {
        client = await tcp.AcceptTcpClientAsync();
        string point = client.Client.RemoteEndPoint.ToString();
        ns = client.GetStream();
        int num = 0;
        string data = string.Empty;
        while ((num = await ns.ReadAsync(bytes, 0, bytes.Length)) != 0)
        {
            string msg = Encoding.UTF8.GetString(bytes, 0, num);
            data += msg;
            Thread.Sleep(10);
        }
    }
    catch (Exception ex)
    {
        logger.Error(ex.ToString());
    }
    finally
    {
        if (ns != null)
            ns.Close();
        if (client != null)
            client.Close();
    }
}

收获点赞: 0

评论

...