简单的多人聊天C#Socket.docx
- 文档编号:18171190
- 上传时间:2023-08-13
- 格式:DOCX
- 页数:18
- 大小:19.06KB
简单的多人聊天C#Socket.docx
《简单的多人聊天C#Socket.docx》由会员分享,可在线阅读,更多相关《简单的多人聊天C#Socket.docx(18页珍藏版)》请在冰点文库上搜索。
简单的多人聊天C#Socket
/********************************8chatserver:
*************************************************/
usingsystem;
usingsystem.drawing;
usingsystem.collections;
usingponentmodel;
usingsystem.windows.forms;
usingsystem.data;
usingsystem.threading;
using.sockets;
using;
namespacechat_server
{
///
///form1的摘要说明。
///
publicclassform1:
system.windows.forms.form
{
///
///必需的设计器变量。
///
privateponentmodel.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(pareto(tokens[3])==0) sendtoclient(cl,clientcommand); if(pareto(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(pareto(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 { using.sockets; using; /// ///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; usingponentmodel; usingsystem.windows.forms; usingsystem.data; usingsystem.io; using; using.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; privateponentmodel.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.dr
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 简单 聊天 Socket