本帖最后由 Blue_Pen 于 2016-10-25 13:38 编辑
BinGoo系列之Socket组件《一、客户端的类库封装》
简介:Sokcet客户端类库的封装,三步走轻松解决客户端socket通讯,客户端dll分装代码总量少至300行(包含所有注释),服务端dll将在下篇文章中公布, 最新全部源码在下篇socket之服务端中 功能介绍:Socket通讯客户端实现网络通讯,支持断开重连。 以下是客户端的分装 用户使用此dll只需 1、实例化:TCPClient_tcpClient = new TCPClient(TxtIp.Text, int.Parse(TxtPort.Text)); 2、调用启动方法:TCPCliet.StartConnection(); Demo代码如下:[C#] 纯文本查看 复制代码 namespace SocketHelperDemo
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
//掩耳盗铃线程控制UI控件
CheckForIllegalCrossThreadCalls = false;
//创建委托接收数据
DelegateHelper.SocketReceive =SocketMessage;
}
/// <summary>
/// 创建TCPClient实例
/// </summary>
private TCPClient _tcpClient;
/// <summary>
/// 初始化并连接TCPClient
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnConClick(object sender, EventArgs e)
{
_tcpClient = new TCPClient(TxtIp.Text, int.Parse(TxtPort.Text));
_tcpClient.StartConnection();
}
/// <summary>
/// 接收Socket数据
/// </summary>
/// <param name="msg"></param>
private void SocketMessage(string msg)
{
//自定义处理接收的数据
MsgInfomationList.Items.Add(msg);
}
/// <summary>
/// 发送Socket数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnSendClick(object sender, EventArgs e)
{
_tcpClient.SendCommand(TxtSendMsg.Text);
}
/// <summary>
/// 退出时关闭所有线程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
{
System.Environment.Exit(0);
}
}
} 封装类库就两个类
封装方法及案例运行效果图 Socket客户端Dll源码及案例下载下载:
|