Home > Blockchain >  How do I make the server respond to all clients?
How do I make the server respond to all clients?

Time:08-17

I have got a simple program going that allows a client to send messages to a server, and the server responds with this code:

requestCount = requestCount   1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, 1000);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> "   "Client "   clNo   " said: '"   dataFromClient   "'.");

//for actual responding
serverResponse = "Client "   clNo   " said: "   dataFromClient;
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();

This works, but it only gives back the response to the client that sent the message. I would like it so that both clients can see each other's messages.

Bonus question!!! I have a website, and I was wondering if there is any way to host it on there so it is not restricted to be used locally.

Thanks!

If you want any more of my code, just ask and I will be happy to give it too you!

CodePudding user response:

It seems like a chat application to me. Since only the sender opens a connection to the server it is normal to be the only one getting the response.

From there the 2nd user needs somehow to be notified about the message. There are 2 ways . Polling & Websockets.

With polling you need to save the messages sent to a db or memory and request every x second for updates.

The 2nd user sends a request for any new messages to the server . If there are new messages since the last time requested the server returns the new messages.

But by far the most professional way to do this is web sockets. With web sockets the server keeps a connection to each user constantly. When a new message is posted , it notifies all other connected users.

SignalR is microsoft's higher level implementation over web sockets. Refer to this tutorial in order to get a better grasp of the technology.

https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc

  • Related