欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#使用Socket实现局域网聊天

程序员文章站 2023-12-18 18:44:22
本文实例为大家分享了c#使用socket实现局域网聊天的具体代码,供大家参考,具体内容如下 先运行一个java写的局域网聊天,效果图如下 后使用c#图形修改如下:...

本文实例为大家分享了c#使用socket实现局域网聊天的具体代码,供大家参考,具体内容如下

先运行一个java写的局域网聊天,效果图如下

C#使用Socket实现局域网聊天

后使用c#图形修改如下:

C#使用Socket实现局域网聊天

c#代码:

servlet服务端

using system; 
using system.collections.generic; 
using system.drawing; 
using system.windows.forms; 
using system.net; 
using system.net.sockets; 
using system.threading; 
using system.io; 
using system.text; 
using system.text.regularexpressions; 
 
namespace server 
{ 
  public partial class mainform : form 
  { 
    private tcplistener listener; 
     
    private dictionary<string,tcpclient> socketlist; 
    private bool tag = true; 
    private stringbuilder charlist; 
     
    public mainform() 
    { 
      initializecomponent(); 
      control.checkforillegalcrossthreadcalls = false; 
    } 
     
    void bu_startclick(object sender, eventargs e) 
    { 
      cb_chatlist.items.clear(); 
      selectchat.text=""; 
      int port = 8888; 
      //创建服务端,并且启动 
      try{ 
        listener = new tcplistener(ipaddress.parse(ipaddress()),port); 
        listener.start();   
         
        bu_start.enabled = false; 
        bu_stop.enabled = true; 
      }catch(exception ex) 
      { 
        messagebox.show("服务器启动失败, 原因:"+ex.message); 
        bu_start.enabled = true; 
        bu_stop.enabled = false; 
        return; 
      } 
      selectchat.text = "服务器启动成功,访问ip:"+ipaddress()+" 端口号:"+port; 
       
      //记录住连接的客户端 
      socketlist = new dictionary<string,tcpclient>(); 
      charlist = new stringbuilder(); 
       
      //使用多线程,用于多个客户端接入 
      thread th = new thread(new threadstart(executetask)); 
      th.start(); 
    } 
    public void executetask() 
    { 
      while(tag) 
      { 
        //等待用户连接 
        tcpclient client = null; 
        try{ 
          client = listener.accepttcpclient(); 
        }catch(exception) 
        { 
        } 
        thread th = new thread(executeread); 
        th.start((object)client); 
      } 
    } 
    public void executeread(object pamars) 
    { 
      //永久监听读取客户端 
      tcpclient client = pamars as tcpclient; 
      while(tag) 
      { 
        networkstream ns = client.getstream(); 
        streamreader sr = new streamreader(ns); 
        string msg = string.empty; 
        string people = string.empty; 
        try { 
          msg = sr.readline(); 
          if(msg.indexof("<clientname>")!=-1) 
          { 
            msg = regex.split(msg,"=")[1]; 
            cb_chatlist.items.add(msg);        
            charlist.append(msg).append("<@>"); 
            socketlist.add(msg,client); 
            msg = "<br>欢迎【"+msg+"】光临<br>"; 
          } 
          selectchat.appendtext(msg.replace("<br>","\r\n")); 
          sendmsg(string.empty,msg); 
        } catch (exception) { 
          //messagebox.show(ex.message.tostring()); 
          break; 
        } 
      } 
    } 
    public void sendmsg(string target,string msg) 
    { 
      if(string.empty!=target) 
      { 
        tcpclient client = socketlist[target]; 
        streamwriter sw = new streamwriter(client.getstream()); 
        sw.writeline(msg); 
        sw.flush();  
      }else{ 
        dictionary<string,tcpclient>.keycollection keycoll = socketlist.keys; 
        foreach (string name in keycoll)  
        { 
          streamwriter sw = new streamwriter(socketlist[name].getstream()); 
          sw.writeline(msg+"<@=@>"+charlist.tostring()); 
          sw.flush();        
        } 
      } 
    } 
    /*根据计算名获取ip地址*/ 
    public string ipaddress() 
    { 
      ipaddress[] address = dns.gethostaddresses(dns.gethostname()); 
      return address[2].tostring(); 
    } 
     
    void serverfromformclosing(object sender, formclosingeventargs e) 
    { 
      e.cancel = false; 
      if(tag) 
        tag = false; 
      if(listener!=null) 
        listener.stop(); 
    } 
     
    void bu_stopclick(object sender, eventargs e) 
    { 
      bu_start.enabled = true; 
      bu_stop.enabled = false; 
      if(tag) 
        tag = false; 
      if(listener!=null) 
        listener.stop(); 
    } 
  } 
} 

client客户端

using system; 
using system.drawing; 
using system.windows.forms; 
using system.threading; 
using system.net; 
using system.net.sockets; 
using system.io; 
using system.text; 
using system.text.regularexpressions; 
 
namespace client 
{ 
  public partial class mainform : form 
  { 
    private system.windows.forms.timer closewindowtimer; 
     
    private streamreader sr; 
    private streamwriter sw; 
    private tcpclient tc; 
    private clientlong cl; 
    private bool tag = true; 
       
    public mainform(tcpclient tcp,clientlong clo) 
    { 
      cl = clo; 
      tc = tcp; 
      initializecomponent(); 
      control.checkforillegalcrossthreadcalls = false; 
      bu_simple.hide(); 
    } 
    void clientfromload(object sender, eventargs e) 
    { 
      piaycheckedchanged(); 
    } 
     
    /*事件方法*/ 
    public void piaycheckedchanged() 
    { 
      closewindowtimer = new system.windows.forms.timer(); 
      closewindowtimer.interval = 1000; 
      closewindowtimer.tick += new eventhandler(theout); 
      closewindowtimer.start(); 
    } 
     
    /*执行的事件*/ 
    public void theout(object source, eventargs e) 
    { 
      //这里单独开一个线程用来显示信息 
      try{ 
        thread t1 = new thread(new threadstart(readmsg)); 
        t1.start(); 
      }catch(exception) 
      { 
      } 
    } 
    void readmsg() 
    { 
      if(tag && tc!=null){ 
        sr = new streamreader(tc.getstream()); 
        string msg = sr.readline(); 
        string[] address = regex.split(msg,"<@=@>"); 
        chattext.appendtext(address[0].replace("<br>","\r\n")); 
        address = regex.split(address[1],"<@>"); 
        cb_chatlist.items.clear(); 
        foreach (string s in address) 
        { 
          if(!string.isnullorempty(s) && s != cl.clientname) 
            cb_chatlist.items.add(s);         
        } 
      } 
    } 
    void button1click(object sender, eventargs e) 
    { 
      if(string.isnullorempty(textbox2.text)){ 
        messagebox.show("请输入消息");return; 
      } 
      sw = new streamwriter(tc.getstream()); 
      sw.writeline("<br>"+cl.clientname+"  "+datetime.now.tostring("yyyy-mm-dd hh:mm:ss")+"<br> "+textbox2.text); 
      textbox2.text = ""; 
      sw.flush(); 
    } 
    void bu_exitclick(object sender, eventargs e) 
    { 
      mainformformclosing(null,null); 
    } 
    void button2click(object sender, eventargs e) 
    { 
      chattext.text = "";  
    } 
    void mainformformclosing(object sender, formclosingeventargs e) 
    { 
      closewindowtimer.stop(); 
      cl.close(); 
      tag = false; 
      if(sr!=null) 
        sr.close(); 
      if(sw!=null) 
        sw.close(); 
    } 
    void bu_simpleclick(object sender, eventargs e) 
    { 
      string selected = cb_chatlist.text; 
      if(selected==null) 
      { 
        messagebox.show("请选择单聊对象"); 
        return; 
      } 
    } 
  } 
} 

补充:

1.上传下载文件、聊天表情、私聊、踢人.......都是可以扩展的功能。

只是目前还没有可执行的思路,希望有相同爱好者多多提出宝贵意见,我会继续关注。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: