Click here to Skip to main content
15,892,005 members

Req feedback: Socket webcam code

Scalee asked:

Open original thread
Hi Coders,

This is my first socket code and i hoping for some feedback/improvements!

I myself think allot of frames go to waste because of incorrect length (i see percentages above 100%), i think the wrong 8 bytes are read.
But i don't know how else to mark the start/end without adding some kind of large delay which would be the same as losing several frames.

Thank you for your time!


Image send code
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
    //Disable new frame event while sending a frame
    if (videoSource != null)
        videoSource.NewFrame -= new NewFrameEventHandler(video_NewFrame);

    Image img = (Image)eventArgs.Frame.Clone();

    NetworkStream nfs = new NetworkStream(camSocket);
    MemoryStream ms = new MemoryStream();

    //Check if already sending a frame
    if (busy == false)
    {
    	//Same image to memory stream
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        //Set boolean to busy
        busy = true;
        int len = 0;
        long rdby = 0;
        byte[] tmp = new byte[8];

        //Send length (8 bytes)
        //Get the length of the memory stream and convert it to 8 bytes and write it to the tmp array
        BitConverter.GetBytes(ms.Length).CopyTo(tmp, 0);
        nfs.Write(tmp, 0, tmp.Length);

        //Send File
        ms.Seek(0, SeekOrigin.Begin);
        tmp = new byte[1024];
        while (rdby < ms.Length && nfs.CanWrite)
        {
            len = ms.Read(tmp, 0, tmp.Length);
            nfs.Write(tmp, 0, len);
            rdby = rdby + len;
        }
        ms.Close();
        busy = false;
        
    }

    //reattach event for new frames
    if (videoSource != null)
        videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
}


Image receive code
public void WaitForData(SocketPacket s)
{
        if (pfnWorkerCallBack == null) 
        {
            pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
        }
//Read 8 bytes (image length)
        s.currentSocket.BeginReceive(s.Buffer, 0, 8, SocketFlags.None, 	pfnWorkerCallBack, s);
}

public void OnDataReceived(IAsyncResult asyn)
{
    SocketPacket s = (SocketPacket)asyn.AsyncState;

    NetworkStream nfs = new NetworkStream(s.currentSocket);

    byte[] tmp = new byte[1024];
    
    //Convert the 8 read bytes (from BeginReceive) to file length
    long length = BitConverter.ToInt64(s.Buffer, 0);
    long read = 0;

    MemoryStream ms = new MemoryStream();
    while (read < length)
    {
        byte[] buffer = new byte[1024];
        int i = nfs.Read(buffer, 0, buffer.Length);
        ms.Write(buffer, 0, i);
        read = read + i;

        //Calculate percentage done
        int pc = (int)(((double)read / (double)length) * 100.00);
		log(pc + "%");
    }

    ms.Seek(0, SeekOrigin.Begin);
    
    //Invoke new frame event
    if (nImage != null)
        nImage(Image.FromStream(ms));

    WaitForData(s);
}


Socket setup
public Webcam()
{
    mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 1402);
    mainSocket.Bind(ipLocal);
    mainSocket.Listen(-1);

    mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}

public void OnClientConnect(IAsyncResult asyn)
{
        Socket workerSocket = mainSocket.EndAccept(asyn);

        SocketPacket SocPkt = new SocketPacket(workerSocket);

        WaitForData(SocPkt);
        mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
Tags: C#, Webcam, Sockets

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900