服务器端界面
代码:
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace 聊天室服务器端
{
public partial class Form1 : Form
{
public int listenport = 8888 ; // 服务器端监听端口
private TcpListener listener; // 服务器监听器
private ArrayList clients; // 已连接客户端数组
private Thread processor; // 主线程
private Socket clientsocket; // 客户端套接字
private Thread clientservice; // 客户端线程
public Form1()
{
InitializeComponent();
textPort.Text = " 8888 " ;
}
private void StartListening()
{
listener = new TcpListener(listenport);
listener.Start();
while ( true )
{
try
{
Socket s = listener.AcceptSocket();
clientsocket = s;
clientservice = new Thread( new ThreadStart(ServiceClient));
clientservice.Start(); // 开始监听
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
// listener.Stop();
}
private void ServiceClient()
{
Socket client = clientsocket;
bool alive = true ;
while (alive)
{
Byte[] buffer = new Byte[ 2048000 ];
client.Receive(buffer);
// string time = System.DateTime.Now.ToString();
string clientcommand = System.Text.Encoding.Default.GetString(buffer);
string [] tokens = clientcommand.Split( new Char[] { ' | ' });
if (tokens[ 0 ] == " CONNECT " )
{
for ( int n = 0 ; n < clients.Count; n ++ )
{
Client cl = (Client)clients[n];
SendToClient(cl, " JOIN| " + tokens[ 1 ]);
}
EndPoint ep = client.RemoteEndPoint;
Client c = new Client(tokens[ 1 ], ep, clientservice, client);
clients.Add(c);
string message = " LISTEN| " + GetChatterList() + " \r\n " ;
SendToClient(c, message);
clientlist.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[ 3 ];
for ( int n = 0 ; n < clients.Count; n ++ )
{
Client cl = (Client)clients[n];
if (cl.Name.CompareTo(tokens[ 3 ]) == 0 )
SendToClient(cl, clientcommand);
if (cl.Name.CompareTo(tokens[ 1 ]) == 0 )
SendToClient(cl, clientcommand);
}
}
if (tokens[ 0 ] == " LEAVE " )
{
int remove = 0 ;
bool found = false ;
int c = clients.Count;
for ( int n = 0 ; n < c; n ++ )
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
if (cl.Name.CompareTo(tokens[ 1 ]) == 0 )
{
remove = n;
found = true ;
clientlist.Items.Remove(cl);
}
}
if (found)
clients.RemoveAt(remove);
client.Close();
alive = false ;
}
}
}
private void SendToClient(Client cl, string message)
{
try
{
byte [] buffer = System.Text.Encoding.Default.GetBytes(message.ToCharArray());
cl.Sock.Send(buffer, buffer.Length, 0 );
}
catch (Exception)
{
cl.Sock.Close();
cl.CLThread.Abort();
clients.Remove(cl);
clientlist.Items.Remove(cl.Name + " : " + cl.Host.ToString());
}
}
private string GetChatterList()
{
string chatters = "" ;
for ( int n = 0 ; n < clients.Count; n ++ )
{
Client cl = (Client)clients[n];
chatters += cl.Name;
chatters += " | " ;
}
chatters.Trim( new char [] { ' | ' });
return chatters;
}
private void button1_Click( object sender, EventArgs e)
{
if (textPort.Text != " 8888 " )
listenport = Convert.ToInt32( textPort.Text);
Control.CheckForIllegalCrossThreadCalls = false ;
clients = new ArrayList(); // 开始一个监听线程
processor = new Thread( new ThreadStart(StartListening));
processor.Start();
MessageBox.Show( " 开始监听! " );
}
}
}
客户端界面:
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using FCG.Windows.Forms;
namespace 聊天室程序
{
public partial class Form1 : Form
{
private int serverport;
private TcpClient clientsocket;
private NetworkStream ns;
private StreamReader sr;
private Thread recThread = null ;
private string serveraddress;
private string clientname;
private bool connected = false ;
public Form1()
{
InitializeComponent();
// btn_savemessage.Enabled = false;
Control.CheckForIllegalCrossThreadCalls = false ;
btn_shutdown.Enabled = false ;
btn_stopconnect.Enabled = false ;
btn_send.Enabled = false ;
radioBtn_public.Checked = true ;
textBox_port.Text = " 8888 " ;
textBox_ip.Text = " 127.0.0.1 " ;
}
protected override void OnClosed(EventArgs e)
{
QuitChat();
if (recThread != null && recThread.IsAlive)
recThread.Abort();
base .OnClosed(e);
}
private void CreateConnection()
{
label_show.Text = " 连接到服务器 " ;
try
{
clientsocket = new TcpClient(serveraddress, serverport);
ns = clientsocket.GetStream();
sr = new StreamReader(ns);
connected = true ;
}
catch (Exception )
{
MessageBox.Show( " 无法连接到服务器 " , " ERROR " , MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
label_show.Text = " 未连接到服务器 " ;
}
}
private void StoreforServer()
{
try
{
string command = " CONNECT| " + textBox_username.Text;
Byte[] outbytes = System.Text.Encoding.Default.GetBytes(command);
ns.Write(outbytes, 0 , outbytes.Length);
string serverresponse = sr.ReadLine();
serverresponse.Trim();
string [] tokens = serverresponse.Split( new Char[] { ' | ' });
if (tokens[ 0 ] == " LISTEN " )
{
label_show.Text = " 连接到服务器 " ;
btn_stopconnect.Enabled = true ;
}
for ( int n = 1 ; n < tokens.Length - 1 ; n ++ )
onlineUser.Items.Add(tokens[n].Trim( new char [] { ' \r ' , ' \n ' }));
// MessageBox.Show(tokens[1]);
this .Text = clientname + " : 连接到服务器 " ;
}
catch (Exception )
{
MessageBox.Show( " 未连接到! " , " Error " , MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
private void ReceiveChat()
{
bool alive = true ;
while (alive)
{
try
{
Byte[] buffer = new Byte[ 2048000 ];
ns.Read(buffer, 0 , buffer.Length);
string time = System.DateTime.Now.ToLongTimeString();
string chatter = System.Text.Encoding.Default.GetString(buffer);
string [] tokens = chatter.Split( new Char[] { ' | ' });
if (tokens[ 0 ] == " CHAT " )
{
allmessage.AppendText(tokens[ 1 ].Trim());
allmessage.AppendText( " " + time + " \r\n " );
allmessage.AppendText(tokens[ 2 ].Trim());
}
if (tokens[ 0 ] == " PRIV " )
{
allmessage.AppendText( " 悄悄话来自 " );
allmessage.AppendText(tokens[ 1 ].Trim());
allmessage.AppendText( " " + time + " \r\n " );
allmessage.AppendText(tokens[ 2 ] + " \r\n " ); // 不同聊天模式token格式不一样
}
if (tokens[ 0 ] == " JOIN " )
{
allmessage.AppendText(time + " " );
allmessage.AppendText(tokens[ 1 ].Trim());
allmessage.AppendText( " 加入聊天室 " + " \r\n " );
string newcomer = tokens[ 1 ].Trim( new char []{ ' \r ' , ' \n ' });
// string newcomer = tokens[1].Trim();
// MessageBox.Show(newcomer);
onlineUser.Items.Add(newcomer);
}
if (tokens[ 0 ] == " LEAVE " )
{
allmessage.AppendText(time + " " );
allmessage.AppendText(tokens[ 1 ].Trim());
allmessage.AppendText( " 退出了聊天室 " + " \r\n " );
string leaver = tokens[ 1 ].Trim( new char []{ ' \r ' , ' \n ' });
for ( int n = 0 ; n < onlineUser.Items.Count ; n ++ )
{
if (onlineUser.Items[n].ToString().CompareTo(leaver ) == 0 )
{
onlineUser.Items.RemoveAt(n);
}
}
}
if (tokens[ 0 ] == " QUIT " )
{
ns.Close();
clientsocket.Close();
alive = false ;
label_show.Text = " 服务器断开 " ;
connected = false ;
btn_send.Enabled = false ;
btn_stopconnect.Enabled = false ;
btn_shutdown.Enabled = false ;
MessageBox.Show( " 服务器断开! " );
}
}
catch (Exception ) { }
}
}
private void QuitChat()
{
if (connected)
{
try
{
string command = " LEAVE| " + clientname;
Byte[] outbytes = System.Text.Encoding.Default.GetBytes(command);
ns.Write(outbytes, 0 , outbytes.Length);
clientsocket.Close();
}
catch (Exception )
{
}
}
if (recThread != null && recThread.IsAlive)
recThread.Abort();
this .Text = " 聊天室客户端 " ;
}
private void btn_connect_Click( object sender, EventArgs e)
{
if (textBox_username.Text == "" || textBox_ip.Text == "" || textBox_port.Text == "" )
{
MessageBox.Show( " 请输入完整信息 " , " Error " ,MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return ;
}
else
{
clientname = textBox_username.Text;
serveraddress = textBox_ip.Text;
serverport = int .Parse(textBox_port.Text);
textBox_ip.Enabled = false ;
textBox_port.Enabled = false ;
textBox_username.Enabled = false ;
}
CreateConnection();
if (connected)
{
StoreforServer();
recThread = new Thread( new ThreadStart(ReceiveChat));
recThread.Start();
btn_send.Enabled = true ;
btn_shutdown.Enabled = true ;
btn_connect.Enabled = false ;
// btn_savemessage.Enabled = true;
richTextBox1.Text = "" ;
}
}
private void btn_send_Click( object sender, EventArgs e)
{
try
{
if (radioBtn_public.Checked)
{
string pubcommand = " CHAT| " + clientname + " | " + richTextBox1.Text + " \r\n " ;
Byte[] outbytes = System.Text.Encoding.Default.GetBytes(pubcommand);
ns.Write(outbytes, 0 , outbytes.Length);
richTextBox1.Text = "" ;
}
else
{
if (onlineUser.SelectedIndex == - 1 )
{
MessageBox.Show( " 请选择需要单独聊天的用户 " , " Error " ,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return ;
}
string destclient = onlineUser.SelectedItem.ToString();
string command = " PRIV| " + clientname + " | " + richTextBox1.Text + " | " + destclient;
Byte[] outbytes = System.Text.Encoding.Default.GetBytes(command);
ns.Write(outbytes, 0 , outbytes.Length);
richTextBox1.Text = "" ;
}
}
catch (Exception )
{
MessageBox.Show( " 失去与服务器的连接 " , " Error " ,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
ns.Close();
clientsocket.Close();
if (recThread != null && recThread.IsAlive)
recThread.Abort();
connected = false ;
label_show.Text = " 未连接到服务器 " ;
}
}
private void message_KeyPress( object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == ' \r ' )
if (connected)
btn_send_Click(sender, e);
else
btn_connect_Click(sender, e);
}
private void btn_stopconnect_Click( object sender, EventArgs e)
{
QuitChat();
btn_stopconnect.Enabled = false ;
btn_connect.Enabled = true ;
btn_send.Enabled = false ;
btn_shutdown.Enabled = false ;
ns.Close();
clientsocket.Close();
recThread.Abort();
connected = false ;
onlineUser.Items.Clear();
label_show.Text = " 未连接到服务器 " ;
textBox_ip.Enabled = true ;
textBox_username.Enabled = true ;
}
}
}