i've created a service, that's starting the server and a thread OnStart, and is closing the server OnStop.
My code is working very well with 1 device that i'm connecting through this port. The second device that i want to connect is not having response from server.
I'm a little begginer, so, can somebody look at my code and say to me what's wrong, and why is not working with multiple clients? or multithreads?
Sorry for my english...i didn't learn it at school :)
Here is the code:
int i;
TcpListener server = new TcpListener(IPAddress.Any, 9101);
NetworkStream stream;
TcpClient client;
byte[] datalength = new byte[4];
public void ServerReadSend() {
stream = client.GetStream();
new Thread(() =>
{
while ((i = stream.Read(datalength, 0, 1)) != 0)
{
byte[] data = new byte[BitConverter.ToInt32(datalength, 0)];
stream.Read(data, 0, data.Length);
d = Encoding.Default.GetString(data);
d = d.Replace("\0", "");
d = d.Replace("\n", "");
SOME CODE HERE
ServerSend(SOME STRING HERE);
}
}).Start();
}
public void ServerSend(string msg)
{
stream = client.GetStream();
byte[] data;
data = Encoding.Default.GetBytes(msg);
int length = data.Length;
byte[] datalength = new byte[4];
datalength = BitConverter.GetBytes(length);
stream.Write(datalength, 0, 1);
stream.Write(data, 0, data.Length);
}
protected override void OnStart(string[] args)
{
server.Start();
new Thread(() =>
{
client = server.AcceptTcpClient();
if (client.Connected)
{
ServerReadSend();
}
}).Start();
}
protected override void OnStop()
{
server.Stop();
server = null;
}
The devices that i'm connecting through port 9101, are scanners, that are reading some information from Database. The information returned from Database is sent by the server back to the client. And is working well with 1 device. So, this is made only ON SCAN. Can we close the connection and add new connection after the server sends the information?