Question async / await TCP listener saving images from cameras

Dangrad

New member
Joined
Apr 12, 2019
Messages
1
Programming Experience
3-5
Hi guys I have a big problem: I have createad a windows form that worked as a Server listening for TCP messages sended by some cameras connected to the same private network. Each camera send a tcp message to the server when the camera detects something, the server has to work continuosly without freezing the gui interface and has to process every TCP message. The processing of this data includes the saving of an image shooted by the sender camera. The server saves these images into a folder and here there is my problem: the server is not able to save correclty each image: it looks like that some bytes have been lost during the trasmission but I think that all the bytes have riched the server, something deeper has happend. Maybe it could be the way that I have programmed the async / await server?

I am following this TCP header ibb.co/c8tJ3fD As you can see bytes from 20 to 24 are for the size of the data message so I convert that for byte for creating my buffer to read the message. Into the data message each field transmitted follows this schema ibb.co/d4L4D75

I have a list of TcpListener because I have to use more server, one for each tab.
Here how the saved images look like
As you can see is not completely saved, except someone for some unkowned reason

Here is the code

ASYNC Part:
public void TcpServer(int port)
    {
        IPAddress ipAddress = null;
        string hostName = Dns.GetHostName();
        IPHostEntry ipHostInfo = Dns.GetHostEntry(hostName);
        for (int i = 0; i < ipHostInfo.AddressList.Length; ++i)
        {
            if (ipHostInfo.AddressList[i].AddressFamily ==
              AddressFamily.InterNetwork)
            {
                ipAddress = ipHostInfo.AddressList[i];
                _listener.Add( new TcpListener(ipAddress, port));
                ReceiveDataAsync();
                break;
            }
        }
        if (ipAddress == null)
            throw new Exception("No IPv4 address for server");
    }
    private async void ReceiveDataAsync()
    {
        try
        {
            _listener[tbServer.SelectedIndex].Start();
            while (true)
            {
                var tcpClient = await _listener[tbServer.SelectedIndex].AcceptTcpClientAsync();
                ReadDataFromClientAsync(tcpClient);
            }
        }
        catch (Exception e)
        {
            MessageBox.Show("Errore: ", e.Message.ToString());
        }
    }
    private async Task ReadDataFromClientAsync(TcpClient client)
    {
        try
        {
            using (NetworkStream stream=client.GetStream())
            {
                int selectedTabIndex, indexOfPort;
                string endPoint;
                while (client.Connected)
                {
                    int count = 0;
                    var countBytes = new byte[4];
                    for (int i = 0; i < 6; i++)
                    {
                        count = await stream.ReadAsync(countBytes, 0, countBytes.Length);
                    }
                    //The data dimension of the TCP message is into his header, 24th byte.
                    if (count == 0)
                    {
                        break;
                    }
                    byte[] bytes = new byte[BitConverter.ToUInt32(countBytes, 0)];
                    await stream.ReadAsync(bytes, 0, bytes.Length);
                    indexOfPort = Settings.getIndexOfPort(client.Client.LocalEndPoint.ToString());
                    endPoint = client.Client.RemoteEndPoint.ToString();
                    selectedTabIndex = Settings.getIndexOfPort(client.Client.LocalEndPoint.ToString());
                    updateGui("entry", indexOfPort,endPoint);
                    BufferData bufferService = new BufferData();
                    CameraMessage cameraMessage = await bufferService.writeBufferData(bytes.ToList());
                    if (cameraMessage == null)
                        return;
                  //doing some stuff
                        msgToShow = await bufferService.SaveImageFromCamera(cameraMessage);
                      //doing other stuff 
                    }
                    client.Close();
                    closeCommunication(selectedTabIndex,indexOfPort,endPoint);
                }
            }
        }
        catch (IOException e)
        {
            updateGui("stop");
        }
    }

BufferData class:
public class BufferData
            {
              public async Task<CameraMessage> writeBufferData(List<byte> bytesList)
          {
        CameraMessage cameraMessage = new CameraMessage();
        try
        {
            int num = 0;
            int startSubData = 0;
            for (int startData = 0; startData < bytesList.Count-8; startData = startSubData + num)
            {
                int codeDataMessage = BitConverter.ToInt32(bytesList.GetRange(startData, 4).ToArray(), 0);
                int indexDataSize = startData + 4;
                int SizeDataMessage = BitConverter.ToInt32(bytesList.GetRange(indexDataSize, 4).ToArray(), 0);
                startSubData = indexDataSize + 4;
                byte[] array = bytesList.GetRange(startSubData, SizeDataMessage).ToArray();
                num = 0;
                switch (codeDataMessage)
                {
                    case 14020:
                        cameraMessage.image = await this.Base64ToImage(array);
                        num = this.OffSetStringType(SizeDataMessage);
                        break;
                }
            }
            return cameraMessage;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
            return null;
        }
    }
    public async Task<string> SaveImageFromCamera( CameraMessage cameraMessage)
    {
        string path = Settings.pathFolder + cameraMessage.ld_I_SN + @"\Images\";
        string res;
        if (!Directory.Exists(Settings.pathFolder+cameraMessage.ld_I_SN))
        {
            Directory.CreateDirectory(Settings.pathFolder + cameraMessage.ld_I_SN + @"\Images");
        }
            try
            {
            await Task.Run(() => { cameraMessage.image.Save(path + cameraMessage.ld_I_FILENAME, ImageFormat.Jpeg); });
                res = "#3 - OK - IMMAGINE SALVATA CON SUCCESSO";
                 cameraMessage.image.Dispose();
            return res;
        }
        catch (Exception ex)
            {
                res = "#3 - ERR - IMMAGINE NON SALVATA";
            return res;
        }
    }
    public async static Task<Image> Base64ToImage(byte[] imageBytes)
    {
        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
        ms.Write(imageBytes, 0, imageBytes.Length);
        return System.Drawing.Image.FromStream(ms, true);
    }
}
 

Latest posts

Back
Top Bottom