F
FLASHCODER
Guest
I have a class where i listen for connections in a separated thread, my problem is that when i try close the socket, comes a exception in Socket.Accept(); that says:
A blocking operation was interrupted by a call to WSACancelBlockingCall
After a seach, i understood that probably this is because i'm closing the socket from another thread (in my case this thread is UI). How i can close and open the socket correctly anytime?
Listener:
class Listener
{
private Socket s;
private bool listening = false;
public bool Running
{
get { return listening; }
}
public Listener()
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void BeginListen(int port)
{
s.Bind(new IPEndPoint(IPAddress.Any, port));
s.Listen(100);
listening = true;
Socket clientSocket = s.Accept();
}
public void StopListen()
{
if (listening == true)
{
s.Close();
listening = false;
}
}
}
frmMain:
public partial class frmMain : Form
{
private Listener listener;
private void frmMain_Load(object sender, EventArgs e)
{
listener = new Listener();
}
private void listen()
{
listener.BeginListen(101);
}
private void stopToolStripMenuItem_Click(object sender, EventArgs e)
{
listener.StopListen();
}
private void tmrcheck_Tick(object sender, EventArgs e)
{
if (listener.Running)
{
startToolStripMenuItem.Enabled = false;
stopToolStripMenuItem.Enabled = true;
}
if (!listener.Running)
{
startToolStripMenuItem.Enabled = true;
stopToolStripMenuItem.Enabled = false;
}
}
}
Continue reading...
A blocking operation was interrupted by a call to WSACancelBlockingCall
After a seach, i understood that probably this is because i'm closing the socket from another thread (in my case this thread is UI). How i can close and open the socket correctly anytime?
Listener:
class Listener
{
private Socket s;
private bool listening = false;
public bool Running
{
get { return listening; }
}
public Listener()
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void BeginListen(int port)
{
s.Bind(new IPEndPoint(IPAddress.Any, port));
s.Listen(100);
listening = true;
Socket clientSocket = s.Accept();
}
public void StopListen()
{
if (listening == true)
{
s.Close();
listening = false;
}
}
}
frmMain:
public partial class frmMain : Form
{
private Listener listener;
private void frmMain_Load(object sender, EventArgs e)
{
listener = new Listener();
}
private void listen()
{
listener.BeginListen(101);
}
private void stopToolStripMenuItem_Click(object sender, EventArgs e)
{
listener.StopListen();
}
private void tmrcheck_Tick(object sender, EventArgs e)
{
if (listener.Running)
{
startToolStripMenuItem.Enabled = false;
stopToolStripMenuItem.Enabled = true;
}
if (!listener.Running)
{
startToolStripMenuItem.Enabled = true;
stopToolStripMenuItem.Enabled = false;
}
}
}
Continue reading...