在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → p2p在线聊天示例源码(对等节点通信)

p2p在线聊天示例源码(对等节点通信)

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:5.12M
  • 下载次数:36
  • 浏览次数:394
  • 发布时间:2018-12-08
  • 实例类别:C#语言基础
  • 发 布 人:陶瓷兔
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 通信 对等节点 局域网

实例介绍

【实例简介】

【实例截图】

from clipboard

from clipboard


from clipboard


开启聊天前 请先开启p2pserver,即:服务端,如下:

from clipboard

【核心代码】

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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
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 Oraycn.MCapture;
using Oraycn.MPlayer;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Security.Cryptography;
 
namespace OnlineChat
{
    public partial class Form1 : Form
    {
        public Login form = null;
        public IAudioPlayer audioPlayer;
        public ICameraCapturer cameracapturer;
        public IMicrophoneCapturer microphoneCapturer;
        private int intPointVariable = 1;//端口增长幅度
        private IPEndPoint ipeLocal;//本地端口
        private IPEndPoint ipeRemote;//指定的远处端口
        private IPEndPoint ipeRemote1;//指定的远处端口
        private IPEndPoint ipeRemote2;//指定的远处端口
        private Socket LocalSocket;//本地套接字,和本地端口绑定
        private long intMaxDataSize = 10000000;//接收缓冲区长度
        private Thread ListenThread;//监听线程1
        private Thread ListenThread_sound;
        private Thread ListenThread_video;
        private byte[] bytData;//数据保存数组
        private EndPoint epRemote;//监听的任意远处端口
        private EndPoint epRemote1;//监听的任意远处端口
        private EndPoint epRemote2;//监听的任意远处端口
        public List<friend> Friends = new List<friend>();
        public friend myself = new friend();
        public List<IPEndPoint> ipeLocals = new List<IPEndPoint>(3);//传文本,传音频,传视频
        public List<Socket> LocalSockets = new List<Socket>(3);//传文本,传音频,传视频
        private string ChatMemberName = null;
        public List<ListItem> list = new List<ListItem>();
        public static Form1 form1;
        bool flag = false;
        public Form1()
        {
            InitializeComponent();
        
            Oraycn.MCapture.GlobalUtil.SetAuthorizedUser("FreeUser", "");
            form = new Login();//定义登录窗体变量
            form.main = this;
            form.Show();
            this.Text = "ChatRoom";
            //本地socket配置
            //循环配置三种不同功能的三个不同Localsocket,//传文本,传音频,传视频
            for (int i = 0, m = 8000; i < 3; i  , m =500)
            {
                //本地socket配置
                ipeLocal = new IPEndPoint(IPAddress.Any, m);//配置本地IP 和 端口,IPAddress.Any表示本机IP
                LocalSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                ipeLocals.Add(ipeLocal);
                LocalSockets.Add(LocalSocket);
                BindSelf(LocalSockets[i], ipeLocals[i]);
            }
 
            //配置远端网口
            epRemote = (EndPoint)(new IPEndPoint(IPAddress.Any, 8000));//任何地方发来的数据都接受
            epRemote1 = (EndPoint)(new IPEndPoint(IPAddress.Any, 8500));//任何地方发来的数据都接受
            epRemote2 = (EndPoint)(new IPEndPoint(IPAddress.Any, 9000));//任何地方发来的数据都接受
            bytData = new byte[intMaxDataSize];
 
            //开始监听
            Listen();
 
         
    }
 
        /// <summary>
        /// 绑定自己的IP和端口
        /// </summary>
        /// <param name="ipe">IP端口对</param>
        /// <returns>绑定成功返回true</returns>
        public string BindSelf(Socket Local,IPEndPoint ipe)
        {
            while (true)
            {
                try
                {
                   Local.Bind(ipe);//socket与本地端点绑定
                   return ipe.Address.ToString()   " : "   ipe.Port;
                }
                catch
                {
                    ipe.Port = ipe.Port   intPointVariable;
                    intPointVariable  ;
                }
            }
        }
 
        private string GetIpAddress()
        {
            string hostName = Dns.GetHostName();   //获取本机名
            IPHostEntry localhost = Dns.GetHostByName(hostName);    //方法已过期,可以获取IPv4的地址
            IPAddress localaddr = localhost.AddressList[localhost.AddressList.Length-1];
            return localaddr.ToString();
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
 
        }
 
 
        /// <summary>
        /// 监听文本方法,用于监听远程发送到本机的信息
        /// </summary>
        public void Listen()
        {
            ListenThread = new Thread(new ThreadStart(DoListen));
            ListenThread.IsBackground = true;//设置为后台线程,这样当主线程结束后,该线程自动结束
            Control.CheckForIllegalCrossThreadCalls = false;
            ListenThread.Start();
        }
 
        /// <summary>
        /// 监听线程
        /// </summary>
        private void DoListen()
        {
            while (true)
            {
                if (LocalSockets[0].Poll(5000, SelectMode.SelectRead))
                {//每5ms查询一下网络,如果有可读数据就接收
                    LocalSockets[0].BeginReceiveFrom(bytData, 0, bytData.Length, SocketFlags.None, ref epRemote, new AsyncCallback(ShowTextData), null);
                }
            }
        }
 
 
        //文本输出函数
        byte[] bytReceivedData;
        private void ShowTextData(IAsyncResult iar)
        {
            int intRecv = 0;
            try
            {
                intRecv = LocalSockets[0].EndReceiveFrom(iar, ref epRemote);
            }
            catch
            {
                throw new Exception();
            }
            if (intRecv > 0)
            {
                bytReceivedData = new byte[intRecv];
                System.Buffer.BlockCopy(bytData, 0, bytReceivedData, 0, intRecv);
                TextView.Items.Add(ChatMemberName   ":"   "\t\t\t"   System.Text.Encoding.UTF8.GetString(bytReceivedData));
            }
        }
        //文本输出函数
        
        private void label2_Click(object sender, EventArgs e)
        {
 
        }        
 
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                { return codec; }
            }
            return null;
        }
 
        private void pictureBox1_Click(object sender, EventArgs e)
        {
 
        }
 
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            form.Close();
        }
        //初始化好友列表
        private void button7_Click(object sender, EventArgs e)
        {
             
            if (Friends.Count != 0)
            {
                listBox1.DisplayMember = "Text";
                listBox1.ValueMember = "Value";
                foreach (friend mem in Friends)
                {
                    list.Add(new ListItem(mem.name, mem.ip));
                }
                listBox1.DataSource = list;
            }
            
        }
 
        private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this.listBox1.SelectedItem != null)
            {
                this.label1.Text = this.listBox1.SelectedValue.ToString();
                ChatMemberName = list[this.listBox1.SelectedIndex].Text.ToString();
            }
        }
 
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            if (this.listBox1.SelectedItem != null)
            {
                this.label1.Text = this.listBox1.SelectedValue.ToString();
                ChatMemberName = list[this.listBox1.SelectedIndex].Text.ToString();
            }
             
        }
 
        private void pictureBox2_Click(object sender, EventArgs e)
        {
 
        }
 
        private void label4_Click(object sender, EventArgs e)
        {
 
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            //Login login = new Login();
            //label6.Text = login.textBox5.Text;
           //label6.Text= myself.name;
        }
 
        private void toolStripContainer1_ContentPanel_Load(object sender, EventArgs e)
        {
 
        }
        //发送消息
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            ipeRemote = new IPEndPoint(IPAddress.Parse(label1.Text.ToString()), 8000);
            if (flag == true)
            {
                byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(textBox4.Text.Trim()); // 将要发送的字符串转换成Utf-8字节数组;
                RijndaelManaged RMCrypto = new RijndaelManaged();
                byte[] Key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
                byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
                RMCrypto.Key = Key;
                RMCrypto.IV = IV;
                RMCrypto.BlockSize = 128;
                RMCrypto.Mode = CipherMode.ECB;
                RMCrypto.Padding = PaddingMode.Zeros;
                byte[] encryptoByte;
                string sMessage = System.Text.Encoding.UTF8.GetString(arrMsg);
                //把明文消息转换成UTF8编码的字节流,避免乱码
                byte[] messageByte = Encoding.UTF8.GetBytes(sMessage);
                //实例化一个MemoryStream用于存放加密后的数据流
                MemoryStream mStream = new MemoryStream();
                //创建用于加密的CryptoStream实例
                CryptoStream CryptStream = new CryptoStream(mStream, RMCrypto.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
                //把明文消息字节流写入到CryptoStream中,进行加密处理
                CryptStream.Write(messageByte, 0, messageByte.Length);
                //把CryptoStream中的数据更新到MemoryStream中
                CryptStream.FlushFinalBlock();
                //把加密后的数据流转换成字节流
                mStream.Close();
                encryptoByte = mStream.ToArray();
                string str = System.Text.Encoding.UTF8.GetString(encryptoByte);
                LocalSockets[0].SendTo(encryptoByte, ipeRemote);
                TextView.Items.Add(myself.name   ":"   "\t\t\t"   str);
                textBox4.Text = null;
            }
            else
            {
                //远端socket配置
                try
                {
                     
                    LocalSockets[0].SendTo(Encoding.UTF8.GetBytes(textBox4.Text), ipeRemote);
                    TextView.Items.Add(myself.name   ":"   "\t\t\t"   textBox4.Text);
                    textBox4.Text = null;
                }
                catch
                {
                    MessageBox.Show("Something Error! Check your IP input.");
                }
            }
        }
        //选择文件
        string filePath = null;
        string fileName = null;
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofDialog = new OpenFileDialog();
            if (ofDialog.ShowDialog(this) == DialogResult.OK)
            {
                fileName = ofDialog.SafeFileName;
                textBox1.Text = fileName;
                filePath = ofDialog.FileName;
            }
        }
        public DateTime GetTime()
        {
            DateTime now = new DateTime();
            now = DateTime.Now;
            return now;
        }
        Socket socketClient = null;
        private void ClientSend(string SendStr, byte symbol)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(SendStr);
            byte[] newBuffer = new byte[buffer.Length 1 ];
            newBuffer[0] = symbol;
            //将从指定偏移量开始的源数组中指定数量的字节复制到以特定偏移量开始的目标数组
            Buffer.BlockCopy(buffer, 0, newBuffer, 1, buffer.Length);
            socketClient.Send(newBuffer);
            TextView.Items.Add(myself.name   GetTime()   "\t\t\t"   SendStr   "\r\n");
            //textBox3.AppendText("客户端A: "   GetTime()   "\r\n"   SendStr   "\r\n");
        }
        private void SendFile(string fileFullPath)
        {
             
        }
        //发送文件
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            SendFile(filePath);
        }
 
        private void textBox4_KeyDown(object sender, KeyEventArgs e)
        {
             
        }
 
        private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                e.Handled = true;
            }
        }
 
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            //this.Visible = false;
            FormRescovery form = new FormRescovery();
            form.Show();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Thread threadClient = null;
            //threadClient = new Thread(RecMsg);
            //threadClient.IsBackground = true;
            //threadClient.Start();
        }
        //加密信息
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            flag = true;
        }
        //解密
        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            MemoryStream encryptoStream = new MemoryStream(bytReceivedData);
            //创建RijndaelManaged实例
            RijndaelManaged RMCrypt = new RijndaelManaged();
            //初始化Key,IV
            byte[] K = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
            byte[] I = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
            RMCrypt.Key = K;
            RMCrypt.IV = I;
            RMCrypt.BlockSize = 128;
            RMCrypt.Mode = CipherMode.ECB;
            RMCrypt.Padding = PaddingMode.Zeros;
            //创建用于解密的CryptoStream实例
            CryptoStream CryptStrea = new CryptoStream(encryptoStream, RMCrypt.CreateDecryptor(K, I), CryptoStreamMode.Read);
 
            //创建StreamReader实例,从CryptoStream中读出数据,
            //StreamReader默认使用UTF8编码读出的数据
            StreamReader SReader = new StreamReader(CryptStrea);
            string strr = SReader.ReadToEnd();
            TextView.Items.Add(ChatMemberName   ":"   "\t\t\t"   strr);
            SReader.Close();
            //encryptoStream.Close();
        }
    }
}


实例下载地址

p2p在线聊天示例源码(对等节点通信)

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

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

网友评论

发表评论

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

查看所有0条评论>>

小贴士

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

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

关于好例子网

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

;
报警