基本信息
源码名称:p2p在线聊天示例源码(对等节点通信)
源码大小:5.12M
文件格式:.zip
开发语言:C#
更新时间:2018-12-08
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
开启聊天前 请先开启p2pserver,即:服务端,如下:
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();
}
}
}