private void EstablishConnection()
{
statusBar1.Text = "正在连接到服务器";
try
{
clientsocket = new TcpClient(serveraddress,serverport);
ns = clientsocket.GetStream();
sr = new StreamReader(ns);
connected = true;
}
catch (Exception)
{
MessageBox.Show("不能连接到服务器!","错误",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
statusBar1.Text = "已断开连接";
}
}
private void RegisterWithServer()
{
lbChatters.Items.Clear();
clientname = clientName.Text;
try
{
string command = "CONN|" + clientname; //+"\r\n";
Byte outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
ns.Write(outbytes,0,outbytes.Length);
string serverresponse = sr.ReadLine();
serverresponse.Trim();
string tokens = serverresponse.Split(''|'');
if(tokens[0] == "LIST")
{
statusBar1.Text = "已连接";
btnDisconnect.Enabled = true;
}
if(tokens != "")
{
for(int n=1; n<tokens.Length;n++)
lbChatters.Items.Add(tokens[n].Trim(new char{''\r'',''\n''}));
}
this.Text = clientname + ":已连接到服务器";
}
catch (Exception ex)
{
MessageBox.Show("注册时发生错误!"+ex.Message,"错误",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
connected = false;
}
}
private void ReceiveChat()
{
bool keepalive = true;
while (keepalive)
{
try
{
Byte buffer = new Byte[1024]; // 2048???
ns.Read(buffer,0,buffer.Length);
string chatter = System.Text.Encoding.ASCII.GetString(buffer);
string tokens = chatter.Split(new Char{''|''});
if (tokens[0] == "CHAT")
{
rtbChatIn.AppendText(tokens);
// if(logging)
// logwriter.WriteLine(tokens);
}
if (tokens[0] == "PRIV")
{
rtbChatIn.AppendText("Private from ");
rtbChatIn.AppendText(tokens.Trim() );
rtbChatIn.AppendText(tokens + "\r\n");
// if(logging)
// {
// logwriter.Write("Private from ");
// logwriter.Write(tokens.Trim() );
// logwriter.WriteLine(tokens + "\r\n");
// }
}
if (tokens[0] == "JOIN")
{
rtbChatIn.AppendText(tokens.Trim() );
rtbChatIn.AppendText(" has joined the Chat\r\n");
// if(logging)
// {
// logwriter.WriteLine(tokens+" has joined the Chat");
// }
string newguy = tokens.Trim(new char{''\r'',''\n''});
lbChatters.Items.Add(newguy);
}
if (tokens[0] == "GONE")
{
rtbChatIn.AppendText(tokens.Trim() );
rtbChatIn.AppendText(" has left the Chat\r\n");
// if(logging)
// {
// logwriter.WriteLine(tokens+" has left the Chat");
// }
lbChatters.Items.Remove(tokens.Trim(new char{''\r'',''\n''}));
}
if (tokens[0] == "QUIT")
{
ns.Close();
clientsocket.Close();
keepalive = false;
statusBar1.Text = "服务器端已停