基本信息
源码名称:c# 高性能 iocp服务端 示例源码
源码大小:0.11M
文件格式:.rar
开发语言:C#
更新时间:2017-12-28
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using IocpServer;
using IocpServer.AsyncSocketServer;
namespace IoServer
{
public enum ProtocolFlag
{
None = 0,
Add = 1,
Remove = 2,
Clear = 3
}
public partial class Form1 : Form
{
//主窗体
public static Form1 mainform = null;
//调试信息窗体
public static MessageBOX messagelist;
//server服务
public static IServerSocket serversocket;
//用户列表 第一个参数是 ConnectID,第二个 参数是用户名
public static Dictionary<string, string> userlistdata = new Dictionary<string, string>();
//获取主窗体
public static Form1 GetMainForm()
{
if (mainform != null)
{
return mainform;
}
return null;
}
//构造函数
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
Form1.mainform = this;
}
public static void Debug(string message)
{
if (messagelist != null)
{
messagelist.AddMessage(message);
}
}
public static void DebugError(string message)
{
if (messagelist != null)
{
messagelist.AddMessage(message);
}
}
public bool SetListBoxUser(string id, string user, ProtocolFlag flag)
{
try
{
lock (((ICollection)userlistdata).SyncRoot)
{
string str = "";
switch (flag)
{
case ProtocolFlag.Add:
if (!userlistdata.TryGetValue(id, out str))
{
userlistdata.Add(id, user);
return true;
}
break;
case ProtocolFlag.Remove:
if (userlistdata.TryGetValue(id, out str))
{
userlistdata.Remove(id);
return true;
}
break;
default:
break;
}
return false;
}
}
catch (Exception ex)
{
Debug("异常来自于 Form1.cs SetListBoxUser " ex.ToString());
return false;
}
}
public void ShowData(Dictionary<string, string> userdata)
{
try
{
listBox1.Items.Clear();
foreach (KeyValuePair<string, string> pair in userdata)
{
obj1 obj = new obj1();
obj.username = pair.Value;
obj.connectid = pair.Key;
listBox1.Items.Add(obj);
//listBox1.Items.Add(pair.Value);
}
if (userdata.Count > 0) listBox1.SelectedIndex = userdata.Count - 1;
}
catch (Exception ex)
{
DebugError("异常来自于 Form1.cs ShowData " ex.ToString());
}
}
/// <summary>
/// 接受到数据事件
/// </summary>
/// <param name="sender"></param>
/// <param name="toker"></param>
public void clientread(object sender, IocpServer.AsyncUserToken toker)
{
try
{
byte[] destArray = new byte[toker.BytesReceived];// 目的字节数组
Array.Copy(toker.ReceiveBuffer, toker.Offset 2, destArray, 0, toker.BytesReceived - 2);
string str = System.Text.Encoding.UTF8.GetString(destArray);
string text = str.Substring(0, toker.BytesReceived - 2);
//string text = str;
//string msg = "接收到用户{0}的消息:{1}";
//msg = string.Format(msg,toker.ConnectionId.ToString(), text);
//Debug("READ " msg);
if (SetListBoxUser(toker.ConnectionId, text, ProtocolFlag.Add) == true)
{
ShowData(userlistdata);
this.toolStripStatusLabel1.Text = "添加新用户:" text;
destArray[toker.BytesReceived - 2] = 0x38;
destArray[toker.BytesReceived - 1] = 0x38;
Form1.serversocket.Send(toker.ConnectionId, destArray);
}
else
{
destArray[toker.BytesReceived - 2] = 0x4E;
destArray[toker.BytesReceived - 1] = 0x6F;
Form1.serversocket.Send(toker.ConnectionId, destArray);
}
//if (str == "login")
//{
// if (SetListBoxUser(toker.ConnectionId, str, ProtocolFlag.Add) == true)
// {
// ShowData(userlistdata);
// this.toolStripStatusLabel1.Text = "添加新用户:" str;
// }
//}
//else if (text == "start")
//{
// text = text.Substring(6, text.Length - 7);
// //由于我们是以逗号分隔的,所以用户提交的逗号,需要替换好,我们替换为了'.'号
// text=text.Replace(',','.');
// userlistdata.Add(toker.ConnectionId, text);
// ShowData(userlistdata);
//}
}
catch (Exception ex)
{
DebugError("异常来自于:Form1.cs 353行 " ex.ToString());
}
System.Threading.Thread.Sleep(10);
}
/// <summary>
/// 断开客户端事件
/// </summary>
/// <param name="sender"></param>
/// <param name="toker"></param>
public void disconnect(object sender, IocpServer.AsyncUserToken toker)
{
try
{
DelClient(toker.ConnectionId);
ShowData(userlistdata);
}
catch (Exception ex)
{
DebugError("异常来自于 From1.cs disconnect " ex.ToString());
}
}
//添加一个用户
public static void AddUser(string connectid,AsyncUserToken token)
{
try
{
Form1 form = Form1.GetMainForm();
if (form != null)
{
form.toolStripStatusLabel1.Text = "一个新的连接";
}
}
catch (Exception ex)
{
DebugError("异常来自于:Form1.cs AddUser " ex.ToString());
}
}
/// <summary>
/// 删除断开的连接
/// </summary>
/// <param name="connectid"></param>
public void DelClient(string connectid)
{
//string msg = "一个用户{0}离开!当前有{1}个用户!";
//msg = string.Format(msg, connectid,serversocket.NumConnectedSockets);
//Debug("DIS " msg);
try
{
Form1 form = Form1.GetMainForm();
if (form != null)
{
form.toolStripStatusLabel1.Text = "一个连接断开";
}
if (SetListBoxUser(connectid, "", ProtocolFlag.Remove) == true)
ShowData(userlistdata);
}
catch (Exception ex)
{
DebugError("异常来自于: Form1.cs DelClient " ex.ToString());
}
}
/// <summary>
/// 启动服务器
/// </summary>
private void StartServer()
{
try
{
int count = 0;
if (!int.TryParse(textBox1.Text, out count))
{
MessageBox.Show("连接数量错误!请重新填写!");
return;
}
int buffersize = 0;
if (!int.TryParse(textBox2.Text, out buffersize))
{
MessageBox.Show("缓冲区填写错误!请重新填写!");
return;
}
serversocket = new IServerSocket(count, buffersize);
serversocket.Init();
int port = 0;
if (!int.TryParse(textBox3.Text, out port))
{
MessageBox.Show("端口填写错误,请重新填写!");
return;
}
serversocket.Start(port);
serversocket.OnClientRead = new EventHandler<IocpServer.AsyncUserToken>(clientread);
serversocket.OnClientDisconnect = new EventHandler<IocpServer.AsyncUserToken>(disconnect);
}
catch (Exception ex)
{
DebugError("服务端启动失败......! 异常来自于 Form1.cs StartServer " ex.ToString());
}
}
//服务器启动
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
//不断获取当前连接数
timer1.Enabled = true;
if (checkBox1.Checked)
{
if (messagelist == null)
{
messagelist = new MessageBOX(this);
}
messagelist.Show();
}
userlistdata.Clear();
listBox1.Items.Clear();
StartServer();
this.toolStripStatusLabel1.Text = "服务器启动成功......!";
}
private void button2_Click(object sender, EventArgs e)
{
this.toolStripStatusLabel1.Text = "服务端已经停止......!";
button2.Enabled = false;
button1.Enabled = true;
serversocket.Shutdown();
}
/// <summary>
/// 单独给某个用户发送消息,或者群发消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
//要发送的数据
string text = textBox4.Text;
byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
//群发
if (checkBox2.Checked)
{
foreach (KeyValuePair<string, string> temp in userlistdata)
{
try
{
Form1.serversocket.Send(temp.Key.ToString(), data);
}
catch (Exception ex)
{
Form1.DebugError(ex.ToString());
}
}
return;
}
int index = this.listBox1.SelectedIndex;
if (index >= 0 && index < this.listBox1.Items.Count)
{
obj1 user = (obj1)this.listBox1.SelectedItem;
serversocket.Send(user.connectid, data);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serversocket != null)
{
label6.Text = serversocket.NumConnectedSockets.ToString();
}
label10.Text = listBox1.Items.Count.ToString();
}
//开启和关闭调试窗口
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
if (messagelist == null)
{
messagelist = new MessageBOX(this);
messagelist.Show();
}
}
else
{
if (messagelist != null)
{
messagelist.Close();
messagelist = null;
}
}
}
public void SetCheckBox(bool flag)
{
if (flag)
{
checkBox1.Checked = true;
}
else
{
checkBox1.Checked = false;
}
}
private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("作者:梦想之家2工作室 阿龙(qq:1357098586,群:63438968)");
}
/// <summary>
/// 搜索用户
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_Click(object sender, EventArgs e)
{
string findname = textBox5.Text;
if (findname == "")
{
return;
}
else
{
int index = listBox1.FindString(findname);
if (index > 0 && index <= listBox1.Items.Count)
listBox1.SetSelected(index, true);
}
}
/// <summary>
/// 剔除一个用户
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
obj1 obj = (obj1)listBox1.SelectedItem;
if (obj != null)
{
serversocket.Disconnect(obj.connectid);
}
}
}
public class obj1
{
public string username;
public string connectid;
public override string ToString()
{
return username;
}
}
}