实例介绍
【实例截图】
开启聊天前 请先开启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();
}
}
}
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论