while (keepalive)
{
Byte buffer = new Byte[1024];
int bufLen = 0;
try
{
bufLen = client.Available ;
client.Receive(buffer,0,bufLen,SocketFlags.None);
if(bufLen==0)
continue;
}
catch(Exception ex)
{
MessageBox.Show("Receive Error:"+ex.Message);
return;
}
string clientcommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0,bufLen);
string tokens = clientcommand.Split(new Char{''|''});
Console.WriteLine(clientcommand);
if (tokens[0] == "CONN")
{
for(int n=0; n<clients.Count;n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, "JOIN|" + tokens);
}
EndPoint ep = client.RemoteEndPoint;
Client c = new Client(tokens, ep, clientservice, client);
string message = "LIST|" + GetChatterList() +"\r\n";
SendToClient(c, message);
clients.Add(c);
lbClients.Items.Add(c);
}
if (tokens[0] == "CHAT")
{
for(int n=0; n<clients.Count;n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
}
}
if (tokens[0] == "PRIV")
{
string destclient = tokens;
for(int n=0; n<clients.Count;n++)
{
Client cl = (Client)clients[n];
if(cl.Name.CompareTo(tokens) == 0)
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens) == 0)
SendToClient(cl, clientcommand);
}
}
if (tokens[0] == "GONE")
{
int remove = 0;
bool found = false;
int c = clients.Count;
for(int n=0; n<clients.Count;n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens) == 0)
{
remove = n;
found = true;
lbClients.Items.Remove(cl);
}
}
if(found)
clients.RemoveAt(remove);
client.Close();
keepalive = false;
}
}
}
private string GetChatterList()
{
string result = "";
for(int i=0;i<clients.Count;i++)
{
result += ((Client)clients[i]).Name+"|";
}
return result;
}
private void SendToClient(Client cl,string clientCommand)
{
Byte message = System.Text.Encoding.ASCII.GetBytes(clientCommand);
Socket s = cl.Sock;
if(s.Connected)
{
s.Send(message,message.Length,0);
}
}
private void Form1_Load(object sender, System.EventArgs e)
{
clients = new ArrayList();
}
private void button1_Click(object sender, System.EventArgs e)
{
threadListen = new Thread(new ThreadStart(StartListening));
threadListen.Start();
}
}
}
/***************************** client类 ********************/
/************************** 放于 chatServer 项目中 *********/
using System;
using System.Threading;
namespace Chat_Server
{
using System.Net.Sockets;
using System.N