Csharp局域网聊天系统.docx
《Csharp局域网聊天系统.docx》由会员分享,可在线阅读,更多相关《Csharp局域网聊天系统.docx(16页珍藏版)》请在冰豆网上搜索。
Csharp局域网聊天系统
多人聊天(C#.Socket).
usingSystem;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Data;
usingSystem.Threading;
usingSystem.Net.Sockets;
usingSystem.Net;
namespaceChat_Server
{
///
///Form1的摘要说明。
///
publicclassForm1:
System.Windows.Forms.Form
{
///
///必需的设计器变量。
///
privateSystem.ComponentModel.Containercomponents=null;
staticintlistenport=6666;
Socketclientsocket;
privateSystem.Windows.Forms.ListBoxlbClients;
ArrayListclients;
privateSystem.Windows.Forms.Buttonbutton1;
Threadclientservice;
privateSystem.Windows.Forms.Labellabel1;
ThreadthreadListen;
publicForm1()
{
InitializeComponent();
}
///
///清理所有正在使用的资源。
///
protectedoverridevoidDispose(booldisposing)
{
if(disposing)
{
if(clientservice!
=null)
{
clientservice.Abort();
}
if(threadListen!
=null)
{
try
{
threadListen.Abort();
}
catch(Exceptionex)
{
threadListen=null;
}
}
if(components!
=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#regionWindows窗体设计器生成的代码
///
///设计器支持所需的方法-不要使用代码编辑器修改
///此方法的内容。
///
privatevoidInitializeComponent()
{
this.lbClients=newSystem.Windows.Forms.ListBox();
this.button1=newSystem.Windows.Forms.Button();
this.label1=newSystem.Windows.Forms.Label();
this.SuspendLayout();
//
//lbClients
//
this.lbClients.ItemHeight=12;
this.lbClients.Location=newSystem.Drawing.Point(16,24);
this.lbClients.Name="lbClients";
this.lbClients.Size=newSystem.Drawing.Size(184,268);
this.lbClients.TabIndex=0;
//
//button1
//
this.button1.Location=newSystem.Drawing.Point(272,56);
this.button1.Name="button1";
this.button1.TabIndex=1;
this.button1.Text="button1";
this.button1.Click+=newSystem.EventHandler(this.button1_Click);
//
//label1
//
this.label1.Location=newSystem.Drawing.Point(240,136);
this.label1.Name="label1";
this.label1.Size=newSystem.Drawing.Size(120,32);
this.label1.TabIndex=2;
this.label1.Text="label1";
//
//Form1
//
this.AutoScaleBaseSize=newSystem.Drawing.Size(6,14);
this.ClientSize=newSystem.Drawing.Size(368,309);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Controls.Add(this.lbClients);
this.Name="Form1";
this.Text="Form1";
this.Load+=newSystem.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
///
///应用程序的主入口点。
///
[STAThread]
staticvoidMain()
{
Application.Run(newForm1());
}
privatevoidStartListening()
{
TcpListenerlistener=newTcpListener(listenport);
listener.Start();
label1.Text="listening....";
while(true)
{
try
{
Sockets=listener.AcceptSocket();
clientsocket=s;
clientservice=newThread(newThreadStart(ServiceClient));
clientservice.Start();
}
catch(Exceptionex)
{
MessageBox.Show("listeningError:
"+ex.Message);
}
}
}
privatevoidServiceClient()
{
Socketclient=clientsocket;
boolkeepalive=true;
while(keepalive)
{
Byte[]buffer=newByte[1024];
intbufLen=0;
try
{
bufLen=client.Available;
client.Receive(buffer,0,bufLen,SocketFlags.None);
if(bufLen==0)
continue;
}
catch(Exceptionex)
{
MessageBox.Show("ReceiveError:
"+ex.Message);
return;
}
stringclientcommand=System.Text.Encoding.ASCII.GetString(buffer).Substring(0,bufLen);
string[]tokens=clientcommand.Split(newChar[]{'|'});
Console.WriteLine(clientcommand);
if(tokens[0]=="CONN")
{
for(intn=0;n {
Clientcl=(Client)clients[n];
SendToClient(cl,"JOIN|"+tokens[1]);
}
EndPointep=client.RemoteEndPoint;
Clientc=newClient(tokens[1],ep,clientservice,client);
stringmessage="LIST|"+GetChatterList()+"/r/n";
SendToClient(c,message);
clients.Add(c);
lbClients.Items.Add(c);
}
if(tokens[0]=="CHAT")
{
for(intn=0;n {
Clientcl=(Client)clients[n];
SendToClient(cl,clientcommand);
}
}
if(tokens[0]=="PRIV")
{
stringdestclient=tokens[3];
for(intn=0;n {
Clientcl=(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]=="GONE")
{
intremove=0;
boolfound=false;
intc=clients.Count;
for(intn=0;n {
Clientcl=(Client)clients[n];
SendToClient(cl,clientcommand);
if(cl.Name.CompareTo(tokens[1])==0)
{
remove=n;
found=true;
lbClients.Items.Remove(cl);
}
}
if(found)
clients.RemoveAt(remove);
client.Close();
keepalive=false;
}
}
}
privatestringGetChatterList()
{
stringresult="";
for(inti=0;i {
result+=((Client)clients[i]).Name+"|";
}
returnresult;
}
privatevoidSendToClient(Clientcl,stringclientCommand)
{
Byte[]message=System.Text.Encoding.ASCII.GetBytes(clientCommand);
Sockets=cl.Sock;
if(s.Connected)
{
s.Send(message,message.Length,0);
}
}
privatevoidForm1_Load(objectsender,System.EventArgse)
{
clients=newArrayList();
}
privatevoidbutton1_Click(objectsender,System.EventArgse)
{
threadListen=newThread(newThreadStart(StartListening));
threadListen.Start();
}
}
}
/*****************************client类********************/
/**************************放于chatServer项目中*********/
usingSystem;
usingSystem.Threading;
namespaceChat_Server
{
usingSystem.Net.Sockets;
usingSystem.Net;
///
///Client的摘要说明。
///
publicclassClient
{
privateThreadclthread;
privateEndPointendpoint;
privatestringname;
privateSocketsock;
publicClient(string_name,EndPoint_endpoint,Thread_thread,Socket_sock)
{
//TODO:
在此处添加构造函数逻辑
clthread=_thread;
endpoint=_endpoint;
name=_name;
sock=_sock;
}
publicoverridestringToString()
{
returnendpoint.ToString()+":
"+name;
}
publicThreadCLThread
{
get{returnclthread;}
set{clthread=value;}
}
publicEndPointHost
{
get{returnendpoint;}
set{endpoint=value;}
}
publicstringName
{
get{returnname;}
set{name=value;}
}
publicSocketSock
{
get{returnsock;}
set{sock=value;}
}
}
}
/*****************************chatClient************************************/
usingSystem;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Data;
usingSystem.IO;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Threading;
namespaceChat_Client
{
///
///Form1的摘要说明。
///
publicclassForm1:
System.Windows.Forms.Form
{
privateSystem.Windows.Forms.CheckBoxcheckBox1;
privateSystem.Windows.Forms.StatusBarstatusBar1;
NetworkStreamns;
StreamReadersr;
TcpClientclientsocket;
boolconnected;
Threadreceive;
stringserveraddress="219.228.231.85";
intserverport=6666;
privateSystem.Windows.Forms.RichTextBoxrtbChatIn;
privateSystem.Windows.Forms.ListBoxlbChatters;
privateSystem.Windows.Forms.TextBoxChatOut;
privateSystem.Windows.Forms.ButtonbtnDisconnect;
privateSystem.Windows.Forms.ButtonbtnSend;
privateSystem.Windows.Forms.TextBoxclientName;
stringclientname;
privateSystem.Windows.Forms.ButtonbtnConnect;
privateSystem.ComponentModel.Containercomponents=null;
publicForm1()
{
InitializeComponent();
}
///
///清理所有正在使用的资源。
///
protectedoverridevoidDispose(booldisposing)
{
if(disposing)
{
if(receive!
=null)
{
QuitChat();
}
if(components!
=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#regionWindows窗体设计器生成的代码
///
///设计器支持所需的方法-不要使用代码编辑器修改
///此方法的内容。
///
privatevoidInitializeComponent()
{
this.lbChatters=newSystem.Windows.Forms.ListBox();
this.rtbChatIn=newSystem.Windows.Forms.RichTextBox();
this.checkBox1=newSystem.Windows.Forms.CheckBox();
this.ChatOut=newSystem.Windows.Forms.TextBox();
this.btnSend=newSystem.Windows.Forms.Button();
this.statusBar1=newSystem.Windows.Forms.StatusBar();
this.btnDisconnect=newSystem.Windows.Forms.Button();
this.clientName=newSystem.Windows.Forms.TextBox();
this.btnConnect=newSystem.Windows.Forms.Button();
this.SuspendLayout();
//
//lbChatters
//
this.lbChatters.ItemHeight=12;
this.lbChatters.Location=newSystem.Drawing.Point(32,40);
this.lbChatters.Name="lbChatters";
this.lbChatters.Size=newSystem.Drawing.Size(112,172);
this.lbChatters.TabIndex=0;
//
//rt