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..)
C#
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespaceChat_Server
{
classProgram
{
privatestatic TcpListener tcpListener;
privatestatic Thread listenThread;
staticvoidMain(string[] args)
{
tcpListener = new TcpListener(IPAddress.Any, 7890);
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
Console.WriteLine(" >> Listening for new connections...");
}
privatestaticvoidListenForClients()
{
tcpListener.Start();
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
Console.WriteLine(" >> New connection detected...");
clientThread.Start(client);
}
}
privatestaticvoidHandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = newbyte[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
Answers
Know the answer? Post it. Somebody with the same question will find it here.
Answers
Know the answer? Post it. Somebody with the same question will find it here.