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)
{
if (videoSource != null)
videoSource.NewFrame -= new NewFrameEventHandler(video_NewFrame);
Image img = (Image)eventArgs.Frame.Clone();
NetworkStream nfs = new NetworkStream(camSocket);
MemoryStream ms = new MemoryStream();
if (busy == false)
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
busy = true;
int len = 0;
long rdby = 0;
byte[] tmp = new byte[8];
BitConverter.GetBytes(ms.Length).CopyTo(tmp, 0);
nfs.Write(tmp, 0, tmp.Length);
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;
}
if (videoSource != null)
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
}
Image receive code
public void WaitForData(SocketPacket s)
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
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];
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;
int pc = (int)(((double)read / (double)length) * 100.00);
log(pc + "%");
}
ms.Seek(0, SeekOrigin.Begin);
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);
}