服务器之家

服务器之家 > 正文

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

时间:2022-02-23 13:34     来源/作者:田埂上的梦想

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

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

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

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

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

c#代码:

servlet服务端

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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客户端

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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.上传下载文件、聊天表情、私聊、踢人.......都是可以扩展的功能。

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

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

原文链接:https://blog.csdn.net/hubiao_0618/article/details/35796919

标签:

相关文章

热门资讯

蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
2022年最旺的微信头像大全 微信头像2022年最新版图片
2022年最旺的微信头像大全 微信头像2022年最新版图片 2022-01-10
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
返回顶部