Socket exception and disconnection when a bitmap is received

  • Thread starter Thread starter FLASHCODER
  • Start date Start date
F

FLASHCODER

Guest
I have a Server where is received strings and bitmap (that is displayed in a PictureBox) in same Socket.

My trouble is that every time when a bitmap is received this cause a exception on Socket, to be more specific in my code this part below is executed ( see Listener.cs, ReadCallback() ) :

catch
{
Disconnected(this, i);
i.sock.Close();
clients.Remove(i);
}

How this can be solved?


Here is all relevante code:

Listener.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

class Listener
{
Socket s;
public List<Info> clients;

public delegate void ReceivedEventHandler(Listener l, Info i, string received);
public event ReceivedEventHandler Received;
public delegate void DisconnectedEventHandler(Listener l, Info i);
public event DisconnectedEventHandler Disconnected;

bool listening = false;

public Listener()
{
clients = new List<Info>();
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}

public bool Running
{
get { return listening; }
}

public void BeginListen(int port)
{
s.Bind(new IPEndPoint(IPAddress.Any, port));
s.Listen(100);
s.BeginAccept(new AsyncCallback(AcceptCallback), s);
listening = true;
}

public void StopListen()
{
if (listening == true)
{
s.Close();
}
}

void AcceptCallback(IAsyncResult ar)
{
Socket handler = (Socket)ar.AsyncState;
Socket sock = handler.EndAccept(ar);
Info i = new Info(sock);
clients.Add(i);

Console.WriteLine("New Connection: " + i.ID.ToString());
i.Send("INFO" + Environment.NewLine);

sock.BeginReceive(i.buffer, 0, i.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), i);
handler.BeginAccept(new AsyncCallback(AcceptCallback), handler);
}

void ReadCallback(IAsyncResult ar)
{
Info i = (Info)ar.AsyncState;
try
{
int rec = i.sock.EndReceive(ar);
if (rec != 0)
{
string data = Encoding.ASCII.GetString(i.buffer, 0, rec);
Received(this, i, data);
}
else
{
Disconnected(this, i);
return;
}

i.sock.BeginReceive(i.buffer, 0, i.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), i);
}
catch
{
Disconnected(this, i);
i.sock.Close();
clients.Remove(i);
}
}
}



Info.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class Info
{
public Socket sock;
public Guid ID;
public string RemoteAddress;
public byte[] buffer = new byte[8192];

public Info(Socket sock)
{
this.sock = sock;
ID = Guid.NewGuid();
RemoteAddress = sock.RemoteEndPoint.ToString();
}

public void Send(string data)
{
byte[] buffer = Encoding.UTF8.GetBytes(data);
sock.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback((ar) =>
{
sock.EndSend(ar);
}), buffer);
}
}


frmMain.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Microsoft.VisualBasic;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Media;
using System.IO;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace MyServer
{
public partial class frmMain : Form
{
Listener server;
Thread startListen;

Bitmap _buffer;

public frmMain()
{
InitializeComponent();
server = new Listener();
}

void updateOnline(int count)
{
tslblOnline.Text = "Online: " + count.ToString();
}

private void startToolStripMenuItem_Click(object sender, EventArgs e)
{
startListen = new Thread(listen);
startListen.Start();
}

void listen()
{
server.BeginListen(int.Parse(Interaction.InputBox("Enter port:", "Select a port", "1997"))); /* Sets a port and begins listening*/;
server.Received += new Listener.ReceivedEventHandler(server_Received);
server.Disconnected += new Listener.DisconnectedEventHandler(server_Disconnected);
}

void server_Disconnected(Listener l, Info i)
{
Invoke(new _Remove(Remove), i);
}

void server_Received(Listener l, Info i, string received)
{
string[] cmd = received.Split('|');

switch (cmd[1])
{
case "CONNECTION":

Invoke(new _Add(Add), i, cmd[2]);

break;

case "PRINT":

//MessageBox.Show("print");

var lengthData = new byte[4];
var lengthBytesRead = 0;

while (lengthBytesRead < lengthData.Length)
{
var read = i.sock.Receive(lengthData, lengthBytesRead, lengthData.Length - lengthBytesRead, SocketFlags.None);
if (read == 0) return;
lengthBytesRead += read;
}
Array.Reverse(lengthData);
var length = BitConverter.ToInt32(lengthData, 0);
var imageData = new byte[length];
var imageBytesRead = 0;

while (imageBytesRead < imageData.Length)
{
var read = i.sock.Receive(imageData, imageBytesRead, imageData.Length - imageBytesRead, SocketFlags.None);
if (read == 0) return;
imageBytesRead += read;
}

using (var stream = new MemoryStream(imageData))
{
var bitmap = new Bitmap(stream);
Invoke(new ImageCompleteDelegate(ImageComplete), new object[] { bitmap });
}

break;
}
}

private delegate void ImageCompleteDelegate(Bitmap bitmap);
private void ImageComplete(Bitmap bitmap)
{
if (_buffer != null)
{
_buffer.Dispose();
}
_buffer = new Bitmap(bitmap);
pictureBox1.Size = _buffer.Size;
pictureBox1.Invalidate();
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (_buffer == null) return;
e.Graphics.DrawImage(_buffer, 0, 0);
}

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}

delegate void _Add(Info i, string device);
void Add(Info i, string device)
{
string[] splitIP = i.RemoteAddress.Split(':');
ListViewItem item = new ListViewItem();

item.Text = i.ID.ToString();
item.SubItems.Add(splitIP[0]);
item.SubItems.Add(device);
item.Tag = i;

lvConnections.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
.SetValue(lvConnections, true, null);

lvConnections.Items.Add(item);

updateOnline(lvConnections.Items.Count);
}

delegate void _Remove(Info i);
void Remove(Info i)
{
foreach (ListViewItem item in lvConnections.Items)
{
if ((Info)item.Tag == i)
{
item.Remove();
updateOnline(lvConnections.Items.Count);
break;
}
}
}
}
}

Continue reading...
 
Back
Top