在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C# 简易聊天软件(socket编程)

C# 简易聊天软件(socket编程)

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.62M
  • 下载次数:130
  • 浏览次数:840
  • 发布时间:2017-06-11
  • 实例类别:C#语言基础
  • 发 布 人:mili
  • 文件格式:.rar
  • 所需积分:2
 相关标签: 聊天 软件

实例介绍

【实例简介】

【实例截图】

【核心代码】


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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
 
namespace SyncChatServer//================================服务器
{
    public partial class Form1 : Form
    {
        //保存用户列表
        private List<User> userList = new List<User>();    
        //监听socket 
        private Socket myListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        private bool isNormalExit = false;
        //端口号
        private static int myprot = 8889;
        //用户人数
        private static int usercount = 0;
 
        public Form1()
        {
            InitializeComponent();
            button2.Enabled=false;
            IPEndPoint ep;
             
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            try
            {
                myListener.Bind(new IPEndPoint(ip, myprot));
                richTextBox1.AppendText("主机IP:"   ip.ToString()   "\n");
            }
            catch {
                richTextBox1.AppendText("绑定失败");
            }
            //===================================================  
             
        }
        //-------------------------------------------向窗口输出信息
        private delegate void buttu_richBoxDelegate(string message);
        private void  buttu_richBox(string message)
        {
            richTextBox1.AppendText(message "\n");
        }
        //=======================================================
        //-------------------------------------------------------监听按键
        private void button1_Click(object sender, EventArgs e)
        {
            isNormalExit = false;
            buttu_richBoxDelegate d=buttu_richBox;
           try
           {
            myListener.Listen(10);
               richTextBox1.Invoke(d,"成功监听.");
 
           }catch{
               richTextBox1.Invoke(d,"监听失败。");
           }
            Thread mhThread=new Thread(ListenClientConnect);
            mhThread.IsBackground=true;
            mhThread.Start();
            button1.Enabled=false;
            button2.Enabled=true;
        }
        //=======================================================
        //-------------------------------------------------------监听事件
        private void ListenClientConnect()
        {
            Socket newClient =null;
            while(isNormalExit==false)
            {
                try
                {
                    newClient=myListener.Accept();
                    if (isNormalExit == true)
                    {
                        newClient.Close();
                        usercount = 0;
                        UserCount(usercount);
                        break;
                    }
                }
                catch
                {
                    break ;
                }
                User user = new User(newClient);
                Thread threadReceive = new Thread(ReceiveData);
                threadReceive.IsBackground=true;
                threadReceive.Start(user);
                 UserCount(  usercount);
            }
        }
        //=======================================================
        //-------------------------------------------------------接收信息函数
        private void ReceiveData(object userState)
        {
            User user =(User)userState;
            Socket client=user.client;
            byte[] result=new byte[2048];
            string receiveString = null;
            int receiveNumber;
            while(isNormalExit==false)
            {
                 
                try
                {
                     receiveNumber = client.Receive(result);
                     receiveString=Encoding.UTF8.GetString(result,0,receiveNumber);
                     //sendMessageTorichBox(receiveString);
                }
                catch
                {
                    if(isNormalExit==false)
                    {
                        sendMessageTorichBox("用户" user.username "已经退出!");
                        RemoveUser(user);
                    }
                    break;
                }
 
                string[] splitString =receiveString.Split(',');
                switch(splitString[0].ToLower())
                {
                    case "login":
                        user.username=splitString[1];
                        user.ip = splitString[2];
                        user.port = int.Parse(splitString[3]);
                        userList.Add(user);
                        AddItemToListBox(user.username);
                        sendToAllClient(user,receiveString);
                        FirstLogin(user);
                         
                        break;
                    case "logout":
                        DeletItemInListBox(user.username);
                        sendToAllClient(user,receiveString);
                        RemoveUser(user);
                        UserCount(--usercount);
                        break;
                    case "talk":
                        multMessage(user,receiveString);
                        break;
                    default:
                        sendMessageTorichBox("不知道什么意思!");
                        break;
                }
            }
        }
        //=============================================================
        private void multMessage(User user,String receiveString)
        {
            string[] splitString = receiveString.Split(',');
            for(int i=1;i<splitString.Length;i=i 3)
            {
                sendMessageTorichBox(string.Format("[{0}] 对 [{1}] 说:", user.username, splitString[i])   splitString[i 1]);
                foreach (User target in userList)
                {
                    if (target.username == splitString[i] && user.username != splitString[i])
                    {
                        SendToClient(target, "talk,"   user.username   ","   splitString[i 1]);
                        break;
                    }
                }
            }
        }
        //=============================================================
        private void SendToClient(User user,string message)
        {
            button_richBoxDelegate d=button_richBox;
             
            Socket socket=user.client;
            try
            {
                socket.Send(Encoding.UTF8.GetBytes(message));
            }
            catch
            {
                richTextBox1.Invoke(d,"发送信息失效。");
            }
        }
 
        private void sendToAllClient(User user,string message)
        {
            string command =message.Split(',')[0].ToLower();
            if(command=="login")
            {
                for(int i=0;i<userList.Count;i  )
                {
                    SendToClient(userList[i],message ",");
                 
                }
            }
            else if(command=="logout")
            {
                for(int i=0;i<userList.Count;i  )
                {
                    if(userList[i].username!=user.username)
                    {
                        SendToClient(userList[i],message);
                    }
                }
            }
        }
 
        private void FirstLogin(User user)
        {  
            for (int i = 0; i < userList.Count; i  )
            {
                 
                if(userList[i].username!=user.username)
                {
                    SendToClient(user,"login," userList[i].username "," userList[i].ip "," userList[i].port ",");
                }
            }
        }
        private delegate void UserCountDelegate(object obj);
        private void UserCount(object obj)
        {
 
            UserCountDelegate d = userCountFunction;
            label3.Invoke(d,obj);
        }
        private void userCountFunction(object obj)
        {
             label3.Text = (int)obj " 人";
        }
        private void RemoveUser(User user)
        {
            userList.Remove(user);
            user.Close();
 
        }
 
        private delegate void button_richBoxDelegate(string str);
        private void sendMessageTorichBox(string str)
        {
            button_richBoxDelegate d=button_richBox;
            richTextBox1.Invoke(d,str);
        }
        private void  button_richBox(string str)
        {
            richTextBox1.AppendText(str "\n");
        }
        private delegate void DeletItem_ListBoxDelegate(string str);
        private void DeletItemInListBox(string str)
        {
            DeletItem_ListBoxDelegate d = DeletItem_ListBox;
            listBox1.Invoke(d,str);
        }
        private void DeletItem_ListBox(string str)
        {
            listBox1.Items.Remove(str);
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
            listBox1.ClearSelected();
  
        }
        private delegate void AddItem_ListBoxDelegate(string str);
         
        private void AddItemToListBox(string str)
        {
            AddItem_ListBoxDelegate d=AddItem_ListBox;
            listBox1.Invoke(d,str);
        }
        private void AddItem_ListBox(string str)
        {
            listBox1.Items.Add(str);
            listBox1.SelectedIndex=listBox1.Items.Count-1;
            listBox1.ClearSelected();
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            sendMessageTorichBox("正在停止服务器,并依次使用户退出!");
            isNormalExit=true;
            for(int i=userList.Count-1;i>=0;i--)
            {
                userList[i].client.Close();
                RemoveUser(userList[i]);
            }
            //myListener.Shutdown(SocketShutdown.Both);
            //myListener.Close();
            button1.Enabled=true;
            button2.Enabled=false;
            CloseConnect();
            //mhThread.Join();
        }
        private delegate void  AddrichTextBox1MassageDelegate(string str);
        private void sendrichTextBox1Massage(string str)
        {
            richTextBox1.AppendText(str "\n");
        }
        private void button3_Click(object sender, EventArgs e)
        {
            AddrichTextBox1MassageDelegate d = sendrichTextBox1Massage;
            if (listBox1.SelectedIndex != -1)
            {
                //SendMessage("talk,"   listBox1.SelectedItem   ","   textBox2.Text);
                //----------------------------------------------------
                if (listBox1.Items.Count > 0)
                {
                    for (int i = 0; i < listBox1.SelectedItems.Count; i  )
                    {
                        for (int j = 0; j < userList.Count; j  )
                        {
                            if (userList[j].username == listBox1.SelectedItems[i].ToString())
                            {
                                SendToClient(userList[j], "talk,Server,"   textBox1.Text);
                                richTextBox1.Invoke(d, "[Server] 对 ["   userList[j].username   "]说:"   textBox1.Text);
                                 
                            }
                        }
                        //SendMessage("talk,"   listBox1.SelectedItems[i].ToString()   ","   textBox2.Text);
                        //richTextBox1.Invoke(d, "我对["   listBox1.SelectedItems[i].ToString()   "]说:"   textBox2.Text);
                    }
                }
                //----------------------------------------------------
 
                /*for(int i=0;i<userList.Count;i  )
                {
                    if(userList[i].username == listBox1.SelectedItem.ToString())
                    {
                      SendToClient(userList[i], "talk,Server,"   textBox1.Text);
                      richTextBox1.Invoke(d, "[Server] 对 [" userList[i].username "]说:" textBox1.Text);
                      textBox1.Clear();
                    }
                }*/
                  textBox1.Clear();
            }
            else
            {
                sendrichTextBox1Massage("请先选择一个对话者.");
            }
        }
 
        private delegate void ClearListBoxItemDelegate();
        private void CloseConnect()
        {
            ClearListBoxItemDelegate d1 = ClearListBoxItemFunction;
            listBox1.Invoke(d1);
            usercount = 0;
            UserCount(usercount);
        }
        private void ClearListBoxItemFunction()
        {
            listBox1.Items.Clear();
        }
 
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
 
        }
 
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
 
        }
 
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
 
        }
    }
}


标签: 聊天 软件

实例下载地址

C# 简易聊天软件(socket编程)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有1条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警