'Using TcpListener.AcceptSocket(); in a separate thread causes the thread to block?
I have tried to work around this as well as debug but I'm at a loose end here :( is there any alternative to using this to check for a client connection? This code works fine in a console application so i am guessing the thread is being blocked, although it may be something else i can't see?
public partial class Form1 : Form
{
Socket s;
Declatation of socket.
private void startButton_Click(object sender, EventArgs e)
{
checkTimer.Enabled = true;
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
Background thread to start on button press.
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
working();
}
Thread runs the "working" method.
private void working()
{
if (threadFirstRun == true)
{
threadFirstRun = false;
}
try
{
String tempAddr = tbAddr.Text;
IPAddress ipAd = IPAddress.Parse("147.197.204.172");
// use local m/c IP address, and
// use the same in the client
String tempPort = tbPort.Text;
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 3000);
/* Start Listeneting at the specified port */
myList.Start();
tcConnection1 = "Console:\n" + "The server is running at port 3000...";
tcConnection2 = "\n" + "The local End point is :" + myList.LocalEndpoint;
tcConnection3 = "\n" + "Waiting for a connection.....";
while (true)
{
s = myList.AcceptSocket();
if (s != null)
{
if (connectionEstab == false)
{
tcEstab = "\n" + "Connection accepted from " + s.RemoteEndPoint;
connectionEstab = true;
}
byte[] b = new byte[100];
int k = s.Receive(b);
//Console.WriteLine("Recieved...");
for (int i = 0; i < k; i++)
{
//Console.Write(Convert.ToChar(b[i]));
tcValue = tcValue + Convert.ToString(b[i]);
valueArray[ii] = (float)Convert.ToDouble(b[i]);
}
tcValue = tcValue + "\n";
ii++;
}
else
{
Thread.Sleep(200);
}
}
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
rtbConsole.Text = rtbConsole.Text + "\n" + "Sent Acknowledgement";
/* clean up */
s.Close();
myList.Stop();
}
catch (Exception ex)
{
tcError = "\n\n" + "Error..... " + ex.StackTrace;
}
}
Working method starts the server and blocks upon calling myList.AcceptSocket();?
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
rtbConsole.Text = rtbConsole.Text + "\n" + "Canceled!";
}
else if (!(e.Error == null))
{
rtbConsole.Text = rtbConsole.Text + "\n\n" + ("Error: " + e.Error.Message);
}
else
{
rtbConsole.Text = rtbConsole.Text + "\n" + "Done!";
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
rtbConsole.Text = rtbConsole.Text + "\n" + (e.ProgressPercentage.ToString() + "%");
}
private void stopButton_Click(object sender, EventArgs e)
{
checkTimer.Enabled = false;
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync();
}
}
Other methods for some completeness.
Sending data from my android device is received by a console app running 1 thread, however nothing seems to happen in this windows form application upon sending data to the same ip and port from the same program on the same device. The separate thread just stays blocked and the android app cannot complete communication to send the data.
Solution 1:[1]
It's supposed to block. It can never return null. (Why is everybody doing this? It's like nobody on the web uses Accept correctly.)
Your problem is that after accepting one connection you process that connection and do nothing to resume accepting. The standard pattern is:
while (true) {
var connectionSocket = listeningSocket.Accept();
ProcessAsynchronously(connectionSocket);
}
Make sure ProcessAsynchronously returns immediately. Start a new Task or use async/await.
As you never exit the while loop you never get to sending data. Move all processing logic into ProcessAsynchronously.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | usr |
