Android Socket Listener Only Runs Once - c#

I have an Android application that is currently using a Socket Listener to listen for incoming connections from a C# application. I am able to get the C# application to send a string to the Android application, but the Socket Listener only seems to accept/execute the necessary code to write the information out only once, but continues to accept incoming connection requests from the C# application.
I have searched through Stackoverflow and spent plenty of time on Google, but can't seem to nail down the exact cause for this issue. Below is my code.
Android Code
public class ScoringActivity extends Activity
{
InputStream is;
private String ipAddress = "";
ProgressDialog progress;
private TextView serverStatus;
// DEFAULT IP
public static String SERVERIP = "10.0.2.2";
// DESIGNATE A PORT
public static final int SERVERPORT = 6000;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.scoring);
Intent intent= getIntent();
ipAddress = intent.getStringExtra("ipAddress");
setProgressBarIndeterminateVisibility(false);
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable
{
public void run()
{
try
{
if (SERVERIP != null)
{
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("Listening on IP: ", SERVERIP + " " + SERVERPORT);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true)
{
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("Connected.","Connected.");
}
});
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)
{
Log.d("ServerActivity", line);
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("In the run method", "in the run method");
}
});
}
in.close();
break;
} catch (Exception e)
{
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("Oops. Connection interrupted. Please reconnect your phones.","Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else
{
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("Couldn't detect internet connection.","Couldn't detect internet connection.");
}
});
}
} catch (Exception e)
{
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("Error","Error");
}
});
e.printStackTrace();
}
}
}
}
C# Code
//ProcessSqlFiles();
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
if (!clientSocket.Connected)
clientSocket.Connect(IPAddress.Parse("127.0.0.1"), 8080);
clientSocket.Send(Encoding.UTF8.GetBytes("Test Input"));
clientSocket.Close();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}

You're breaking out of the loop:
}
in.close();
break;
Remove the break statement. I think what you may want is continue assuming you want to go back to the start of the infinite loop.

Related

can not connect to server after some time

Client :
public class TCPClientWrapper : IDisposable
{
private TcpClient tcpClient;
private readonly string address;
private readonly int port;
public TCPClientWrapper(string address, int port)
{
tcpClient = new TcpClient();
this.address = address;
this.port = port;
}
private void TryConnect()
{
tcpClient = new TcpClient();
tcpClient.SendTimeout = 15;
bool isConnected = false;
while (true)
{
try
{
Log.Info("TcpClient, Trying Connect");
tcpClient.Connect(IPAddress.Parse(address), port);
if (SocketConnected(tcpClient.Client))
{
Log.Info("TcpClient, Connected");
isConnected = true;
break;
}
}
catch (Exception e)
{
Log.Info("TcpClient, connection failed. Try to reconnect after 30 seconds, {0}", e.Message);
}
finally
{
if (!isConnected)
Thread.Sleep(30000);
}
}
}
public void SendMessage(string msg)
{
if (!SocketConnected(tcpClient.Client))
{
TryConnect();
}
byte[] buffer = Encoding.UTF8.GetBytes(msg);
tcpClient.Client.Send(buffer);
}
private bool SocketConnected(Socket s)
{
if (!s.Connected)
return false;
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = s.Available == 0;
return !(part1 && part2);
}
public void Dispose()
{
tcpClient.Close();
}
}
Server running as windows service:
public class TcpServer
{
private bool started;
private bool stopped;
private TcpListener tcpListener;
private static ManualResetEvent allDone = new ManualResetEvent(false);
public TcpServer(string url, int port)
{
tcpListener = new TcpListener(IPAddress.Parse(url), port);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Run()
{
if (started) return;
stopped = false;
tcpListener.Start();
Task.Run(() =>
{
Log.Info("Server running");
while (!stopped)
{
allDone.Reset();
tcpListener.BeginAcceptSocket(AcceptCallback, tcpListener);
Log.Info("Accepting socket");
allDone.WaitOne();
}
});
Log.Info("Ping server started");
started = true;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Stop()
{
if (!started) return;
stopped = true;
tcpListener.Stop();
started = false;
Log.Info("Ping server stopped");
}
private void AcceptCallback(IAsyncResult result)
{
try
{
allDone.Set();
if (stopped) return;
Log.Info("Socket accepted");
var listener = (TcpListener)result.AsyncState;
var socket = listener.EndAcceptSocket(result);
Log.Info("Process socket");
ProcessSocket(socket);
}
catch (Exception e)
{
Log.Info("Error accepting callback. {0}", e.Message);
}
}
private void ProcessSocket(Socket socket)
{
try
{
byte[] buffer = new byte[256];
while (!stopped && socket.Receive(buffer) != 0)
{
var msg = Encoding.UTF8.GetString(buffer);
Console.WriteLine(msg);
}
}
catch (Exception e)
{
socket.Close();
Log.Info("Socket closed:{0}", !socket.Connected);
}
}
}
The server is configured in such a way that request to server processed on one IP xxx.xx.xxx.135:5050 and response from server given from xxx.xx.xxx.134:5050
The client works fine for some period of time, but after i get the following error on client side:
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond
xxx.xx.xxx.135:5050
What is the reason that the client can't connect to server ?
Check firewall settings on production server
Check whether IP white listing is required
Antivirus might be blocking the request
If no luck, install Advanced REST Client tool on Chrome and manually
test the request
https://forums.asp.net/t/2138734.aspx?A+connection+attempt+failed+because+the+connected+party+did+not+properly+respond+after+a+period+of+time

Android socket connection with a server

I'm trying to connect my Android phone with a Server. On the Server runs a program written in C#. I've tryed to make it with the following code but it doesn't work.
This is the Android code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Socket socket;
int port = 52301;
String ip = "79.16.115.30";
Button b = (Button) findViewById(R.id.myButton);
assert b != null;
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
byte[] b = ip.getBytes();
/*SocketAddress socketAddress = new InetSocketAddress(ip, port);
socket.connect(socketAddress);*/
socket = new Socket(ip, port);
Toast.makeText(v.getContext(), "CONNESSO", Toast.LENGTH_SHORT).show();
} catch (UnknownHostException e) {
Toast.makeText(v.getContext(), "CHI MINCHIA รจ COSTUI", Toast.LENGTH_SHORT).show();
}catch(IOException e) {
Toast.makeText(v.getContext(), "NO I/O", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
String cause = "Message: " + e.getMessage();
Toast.makeText(v.getContext(), cause, Toast.LENGTH_SHORT).show();
}
}
});
}
I've tryed also to use the code commented but it doesn't work;
This is the program that runs on the Server:
static void Main(string[] args)
{
string ip = Get_external_ip();
int port = 52301;
int max = 10;
IPAddress ipAddress = IPAddress.Parse("192.168.1.56");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); //setto i parametri del socket
Socket sockServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //creo il socket
Socket client;
Console.WriteLine(ip);
try
{
sockServer.Bind(localEndPoint);
sockServer.Listen(max);
while (true)
{
client = sockServer.Accept();
Console.WriteLine(client.RemoteEndPoint.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
private static string Get_external_ip()
{
try
{
WebClient client = new WebClient();
return client.DownloadString("http://icanhazip.com/").TrimEnd('\r', '\n');
}
catch (Exception e)
{
return e.Message;
}
}
First of all, use background Thread for network.
I will give you my working snippet. Try to apply it for your needs.
public class YourClass {
//Server socket variables
private ServerSocket serverSocket;
private DataOutputStream dataOutputStream;
private DataInputStream dataInputStream;
private Socket client;
....
private class SocketServerThread extends Thread {
private int port;
private SocketServerThread(int port) {
this.port = port;
}
#Override
public void run() {
dataInputStream = null;
dataOutputStream = null;
try {
serverSocket = new ServerSocket(port);
isSockedOpened = true;
client = serverSocket.accept(); //wait for client
isClientConnected = true;
Log.d(TAG, "Client connected: " + client.getInetAddress().getHostAddress());
dataInputStream = new DataInputStream(
client.getInputStream());
dataOutputStream = new DataOutputStream(
client.getOutputStream());
String messageFromClient;
while (isClientConnected) {
messageFromClient = dataInputStream.readLine();
handleIncomingMessage(messageFromClient);
}
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage());
}
}
}
To open connection:
public void connect(int port) {
this.port = port;
Thread socketServerThread = new Thread(new SocketServerThread(port));
socketServerThread.start();
}
That's how you check if client connected;
public boolean isConnected() {
return serverSocket.isBound() || client.isConnected();
}
To disconnect:
public void disconnect(boolean needsGathering) {
if (isSockedOpened) {
try {
if (serverSocket != null) {
serverSocket.close();
}
if (dataOutputStream != null) {
dataOutputStream.close();
}
if (dataInputStream != null) {
dataInputStream.close();
}
if (client != null) {
client.close();
}
} catch (IOException e) {
Log.e(TAG, "Couldn't get I/O for the connection");
Log.e(TAG, e.getMessage());
}
} else {
Log.d(TAG, "Socket was not opened");
}
}
}

UDP not receiving updated values

My udp class is not receiving the updated value from the stream. Device sends data continuously and when any alarm activated it add the code in stream and sends the updated value but my class is not receiving the updated value unless I restart the program.
here is my UDPListener class.
public class
{
public static int PORT_NUMBER { get; set; }
public string IpAddress { get; set; }
private readonly UdpClient udp;
public event Action<object, EventArgs> msgChanged;
IAsyncResult ar_ = null;
public UDPListener(string ipaddr, int port)
{
IpAddress = ipaddr;
PORT_NUMBER = port;
udp = new UdpClient(PORT_NUMBER);
Start();
}
public void Start()
{
StartListening();
}
public void Stop()
{
try
{
udp.Close();
}
catch { /* not necessary */ }
}
private void StartListening()
{
ar_ = udp.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
try
{
Thread.Sleep(150);
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(IpAddress), PORT_NUMBER);
byte[] bytes = udp.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
//raise event..
if (message.StartsWith("S"))
if (msgChanged != null)
msgChanged(message, EventArgs.Empty);
}
catch (Exception ex)
{
Debug.WriteLine("Error in UDPListner..." + ex.Message);
}
finally
{
StartListening();
}
}
}
Now what is happening when the program starts it will receive data "S0000.." but when alarm raises data changes to "S8000..etc" but this class continuously receiving the same "S000.." data unless I restart the class.
When I run the udp listener in while loop its works perfectly fine, it receives the updated stream and changes when alarm goes off.
here is the code for while loop udp.
while (!StopRunning)
{
Thread.Sleep(150);
udp = new UdpClient(PORT_NUMBER, AddressFamily.InterNetwork);
var ep = default(IPEndPoint);
var data = udp.Receive(ref ep);
udp.Close();
string msg = Encoding.ASCII.GetString(data);
if (msgChanged != null)
msgChanged(msg, EventArgs.Empty);
}
But I cannot make use of while loop because I have to fit this program in window service.
The main difference in your UDPListener and while loop is that in loop you are creating udp variable each time you are connecting to the UDP:
udp = new UdpClient(PORT_NUMBER, AddressFamily.InterNetwork);
In Receive(IAsyncResult ar) you only connect with the same client, so you still have the same data.
I think that you can rewrite your class something like this:
private void StartListening()
{
udp = new UdpClient(PORT_NUMBER, AddressFamily.InterNetwork);
ar_ = udp.BeginReceive(Receive, new object());
}
Make sure that you're disposing the udp connection after receive with Close() method:
byte[] bytes = udp.EndReceive(ar, ref ip);
udp.Close();

Android Video Streaming Using DatagramSocket setPreviewCallback

I've made an application that obeys UDP using Datagram Socket in android. I'm trying to use Camera's setPreviewCallback function to send bytes to a (c#) client, using Datagram Socket;
But,
The problem is : it throws an exception "The datagram was too big to fit the specified buffer,so truncated" and no bytes are received on client.
I've changed the size of buffer to different values but none work. Now :
Is Datagram approach is right?
What alternatives/approach I'd use to achieve the task?
What's the ideal solution for this?
Android Server :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView = (VideoView) findViewById(R.id.videoView1);
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
setTitle(GetCurrentIP());
mainList = new LinkedList<byte[]>();
secondaryList = new LinkedList<byte[]>();
mCam = null;
mCam = Camera.open();
if (mCam == null) {
Msg("Camera is null");
} else {
if (!Bind()) {
Msg("Bind Error.");
} else {
Msg("Bound Success.");
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mCam.setPreviewDisplay(videoView.getHolder());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Msg(e1.getMessage());
}
mCam.setPreviewCallback(new PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO Auto-generated method stub
DatagramPacket pack;
try {
pack = new DatagramPacket(data, data.length, InetAddress.getByName(clientIP), clientPort);
me.send(pack);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Msg(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Msg(e.getMessage());
}
}
});
mCam.startPreview();
}
});
}
}
}
private boolean Bind(){
try {
me = new DatagramSocket(MY_PORT);
return true;
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Msg(e.getMessage());
}
return false;
}
private String GetCurrentIP(){
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
return Formatter.formatIpAddress(wifiMgr.getConnectionInfo().getIpAddress());
}
public void Msg(String msg){
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
Log.v(">>>>>", msg);
}
}
C# client :
public partial class Form1 : Form
{
const int MY_PORT = 55566;
IPAddress MY_IP;
Thread Receiver;
Socket me;
EndPoint myEndPoint;
EndPoint serverEndPoint;
byte[] buffer;
public Form1()
{
InitializeComponent();
}
private IPAddress GetCurrentIPAddress()
{
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
var selectedIPs = from ip in ips
where ip.AddressFamily == AddressFamily.InterNetwork
select ip;
return selectedIPs.First();
}
private bool Bind()
{
try
{
myEndPoint = new IPEndPoint(MY_IP, MY_PORT);
me.Bind(myEndPoint);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
MY_IP = GetCurrentIPAddress();
this.Text = MY_IP.ToString()+":"+MY_PORT;
me = new Socket
(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp
);
if (!Bind())
Task.Run(()=> MessageBox.Show("Bind() error."));
else
Task.Run(() => MessageBox.Show("Bind success."));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//private void AddToListBox(String msg)
//{
// this.Invoke((Action)delegate() { this.listBox1.Items.Add((this.listBox1.Items.Count+1)+" : "+msg); });
//}
private void buttonStart_Click(object sender, EventArgs e)
{
serverEndPoint = new IPEndPoint(IPAddress.Parse(textBoxmyIP.Text), int.Parse(textBoxmyPort.Text));
Receiver = new Thread(new ThreadStart(Receive));
Receiver.Start();
}
private Image ByteToImage(byte[] bytes)
{
MemoryStream ms = new MemoryStream(bytes);
return Image.FromStream(ms);
}
private void Receive()
{
while (true)
{
buffer = new byte[100];
int nobs = me.ReceiveFrom(buffer, ref serverEndPoint);
if (nobs>0)
{
Task.Run(() => MessageBox.Show("Bytes received"));
//AddToListBox(Encoding.Default.GetString(buffer));
//AddToPictureBox(buffer);
}
Thread.Sleep(100);
}
}
private void AddToPictureBox(byte[] buffer)
{
this.BeginInvoke
(
(Action)
delegate()
{
pictureBox1.Image = ByteToImage(buffer);
}
);
}
}

Network stream write is blocked

I am working on a c# application (.net 4) that accepts multiple tcp connections from different clients. There is a single tcp listener that accepts socket. Communication b/w nodes in duplex. Data is sent using Networkstream.Write method and read using Networkstream.read method. For each tcp connection a seperate thread is created.
The problem is, a few days ago we noticed that one of the clients stopped reading data (due to a bug) for 20 minutes. As the connection was not broken, there was no (IO) exception at the server. However, we noticed that data at the other clients was also not going. After 20 minutes, that client again started receiving the data and soon other clients also started receiving the data.
I know that Network stream's write method is a blocking method and we are not using any timeouts. So there is a potential that write has blocked (described here). But as I understood it, there has to be a seperate write buffer for each tcp connection or is there something more at play. Can a send blockage at a tcp connection, effect other tcp connections in the same application?
Here is the pseudo code for write operation. For each connection there is a seperate outgoing queue process by a seperate thread.
public class TCPServerListener : baseConnection
{
private readonly int _Port;
private TcpListener _tcpListener;
private Thread _thread;
private List<TcpClientData> _tcpClientDataList = new List<TcpClientData>();
private long _messageDiscardTimeout;
private bool LoopForClientConnection = true;
public TCPServerListener(int port, ThreadPriority threadPriority)
{
try
{
// init property
}
catch (Exception ex)
{
// log
}
}
public void SendMessageToAll(int type)
{
base.EnqueueMessageToSend(type, _tcpClientDataList);
}
public void SendMessageToList(int type, IList<TcpClient> tcpClientList)
{
base.EnqueueMessageToSend(type, tcpClientList);
}
public void SendMessage(int type, TcpClient tcpClient)
{
base.EnqueueMessageToSend(type, tcpClient);
}
private void AcceptClientConnections()
{
while (LoopForClientConnection)
{
try
{
Socket socket = _tcpListener.AcceptSocket();
TcpClientData tcpClientData = new TcpClientData();
tcpClientData.tcpClientThread = new Thread(new ParameterizedThreadStart(StartAsync));
tcpClientData.tcpClientThread.Priority = _threadPriority;
tcpClientData.tcpClientThread.IsBackground = true;
tcpClientData.tcpClientThread.Name = "CD" + tcpClientData.tcpClientThread.ManagedThreadId;
tcpClientData.tcpClient = new TcpClient();
tcpClientData.tcpClient.Client = socket;
_tcpClientDataList.Add(tcpClientData);
tcpClientData.tcpClientThread.Start(tcpClientData.tcpClient);
}
catch (ThreadAbortException ex)
{
//log
}
catch (Exception ex)
{
//log
}
}
}
public override void Start()
{
base.Start();
_tcpListener = new TcpListener(System.Net.IPAddress.Any, _Port);
_thread = new Thread(AcceptClientConnections);
_thread.Priority = _threadPriority;
_thread.IsBackground = true;
_tcpListener.Start();
_thread.Start();
}
public override void Stop()
{
// stop listener and terminate threads
}
}
public class baseConnection
{
private Thread _InCommingThread;
private Thread _OutGoingThread;
protected ThreadPriority _threadPriority;
protected BlockingCollection<MessageReceived> _InComingMessageQueue = new BlockingCollection<MessageReceived>();
protected BlockingCollection<MessageToSend> _OutgoingMessageQueue = new BlockingCollection<MessageToSend>();
public void StartAsync(Object oTcpClient)
{
TcpClient tcpClient = oTcpClient as TcpClient;
if (tcpClient == null)
return;
using (tcpClient)
{
using (NetworkStream stream = tcpClient.GetStream())
{
stream.ReadTimeout = Timeout.Infinite;
stream.WriteTimeout = Timeout.Infinite;
BinaryReader bodyReader = new BinaryReader(stream);
while (tcpClient.Connected)
{
try
{
int messageType = bodyReader.ReadInt32();
// checks to verify messages
// enqueue message in incoming queue
_InComingMessageQueue.Add(new MessageReceived(messageType, tcpClient));
}
catch (EndOfStreamException ex)
{
// log
break;
}
catch (Exception ex)
{
// log
Thread.Sleep(100);
}
}
//RaiseDisconnected(tcpClient);
}
}
}
public virtual void Start()
{
_InCommingThread = new Thread(HandleInCommingMessnge);
_InCommingThread.Priority = _threadPriority;
_InCommingThread.IsBackground = true;
_InCommingThread.Start();
_OutGoingThread = new Thread(HandleOutgoingQueue);
_OutGoingThread.Priority = _threadPriority;
_OutGoingThread.IsBackground = true;
_OutGoingThread.Start();
}
public virtual void Stop()
{
// stop the threads and free up resources
}
protected void EnqueueMessageToSend(int type, List<TcpClientData> tcpClientDataList)
{
tcpClientDataList.ForEach(x => _OutgoingMessageQueue.Add(new MessageToSend(type, x.tcpClient)));
}
protected void EnqueueMessageToSend(int type, IList<TcpClient> tcpClientList)
{
foreach (TcpClient tcpClient in tcpClientList)
{
_OutgoingMessageQueue.Add(new MessageToSend(type, tcpClient));
}
}
protected void EnqueueMessageToSend(int type, TcpClient tcpClient)
{
_OutgoingMessageQueue.Add(new MessageToSend(type, tcpClient));
}
private void HandleOutgoingQueue()
{
while (true)
{
try
{
MessageToSend message = _OutgoingMessageQueue.Take();
if (message.tcpClient.Connected)
{
BinaryWriter writer = new BinaryWriter(message.tcpClient.GetStream());
writer.Write(message.type);
}
}
catch (ThreadAbortException ex)
{
// log
return;
}
catch (Exception ex)
{
//_logger.Error(ex.Message, ex);
}
}
}
private void HandleInCommingMessnge()
{
while (true)
{
try
{
MessageReceived messageReceived = _InComingMessageQueue.Take();
// handle message
}
catch (ThreadAbortException ex)
{
// log
return;
}
catch (Exception ex)
{
// log
//_logger.Error(ex.Message, ex);
}
}
}
public class MessageReceived
{
public MessageReceived(int type, TcpClient tcpClient)
{
this.tcpClient = tcpClient;
this.type = type;
}
public int type;
public TcpClient tcpClient;
}
public class MessageToSend
{
public MessageToSend(int type, TcpClient tcpClient)
{
this.tcpClient = tcpClient;
this.type = type;
}
public int type;
public TcpClient tcpClient;
}
public class TcpClientData
{
public Thread tcpClientThread;
public TcpClient tcpClient;
}
}
You mention that for each connection a separate thread is created, but the code you have shown seems to be able to dequeue a message for any connection.
If this code is running on multiple threads, the program will block as soon as every thread is currently trying to send a message to the blocking connection. Another problem you may face if this loop runs on multiple threads is that messages may not arrive in the correct order for the same connection.

Categories