I'm working on a chatbox app using C# on Visual Studio. I have a console server and a chat with a graphical interface. I succeed to send data : chatbox -> server. And also server -> chatbox but only for the chatbox that has sent the info (When chatbox has sent an info, the server has to send it to everyone, but it works only for the sender). I want that all app receive the info. Actually : App 1 -> Server Server -> App 1 Not App 2 I don't understand why. Thanks for your future help.
public void start()
{
TcpListener l = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), port);
l.Start();
while(true)
{
TcpClient comm = l.AcceptTcpClient();
Console.WriteLine("Connection established @" + comm);
new Thread(new Receiver(comm).doOperation).Start();
}
}
class Receiver
{
private TcpClient comm;
public Receiver(TcpClient s)
{
comm = s;
}
public void doOperation()
{
Semaphore s = new Semaphore(1, 1);
while (true)
{
s.WaitOne();
NetworkStream nwStream = comm.GetStream();
byte[] buffer = new byte[comm.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, comm.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received " + dataReceived);
s.Release();
s.WaitOne();
Console.WriteLine("Send to all : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
s.Release();
}
}
}
And I receive the info on the chatbox:
public Form1(string h, int p)
{
...
comm = new TcpClient(h, p);
nwStream = comm.GetStream();
Thread th1 = new Thread(receive);
th1.Start();
}
public void receive()
{
while (true)
{
byte[] bytesToRead = new byte[comm.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, comm.ReceiveBufferSize);
MessageBox.Show("Appli info received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
}
}