Hi All,
I am messing around with a tcp 'chat' server/client program.. I can connect my multiple clients to my server console app just fine, and send and receive data just fine as well... the problem I am running into now is how I can store and then manage those connected clients.
I am accepting clients using the code below.. I'm guessing I need to take the client object and store in an arraylist along with some other association field so that I can loop through the array list when I need to send something to a specific client.. (i.e. like a private message or whisper..)
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading;
namespace Chat_Server { class Program { private static TcpListener tcpListener; private static Thread listenThread;
static void Main(string[] args) { tcpListener = new TcpListener(IPAddress.Any, 7890); listenThread = new Thread(new ThreadStart(ListenForClients)); listenThread.Start();
Console.WriteLine(" >> Listening for new connections..."); }
private static void ListenForClients() { tcpListener.Start();
while (true) { TcpClient client = tcpListener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); Console.WriteLine(" >> New connection detected...");
clientThread.Start(client); } }
private static void HandleClientComm(object client) { TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096]; int bytesRead;
while (true) { bytesRead = 0;
try { // Blocks Until a Client Sends a Message // bytesRead = clientStream.Read(message, 0, 4096); } catch { // Socket Error // Console.WriteLine(" >> SERVER: Socket Exception while handling client communications.."); break; }
if (bytesRead == 0) { // Client Has Disconnected From Server // Console.WriteLine(" >> SERVER: Client has disconnected from the server.."); break; }
// Message Has Been Received // ASCIIEncoding encoder = new ASCIIEncoding(); string strData = encoder.GetString(message, 0, bytesRead).ToString(); Console.WriteLine(strData); }
tcpClient.Close(); } } }
|
Any suggestions or input on this?? Thanks so much for the help.
Jordan