using HPSocketCS;
|
using System.Runtime.InteropServices;
|
namespace iWareCc.Util
|
{
|
/// <summary>
|
/// Socket帮助抽象类,该类实现Socket的连接,关闭基本功能
|
/// </summary>
|
public abstract class SocketClient
|
{
|
/// <summary>
|
/// socket连接客户端
|
/// </summary>
|
public TcpClient Client;
|
|
/// <summary>
|
/// 需要连接的服务器IP
|
/// </summary>
|
private string Ip;
|
|
/// <summary>
|
/// 需要连接的服务器端口
|
/// </summary>
|
private ushort Port;
|
|
/// <summary>
|
/// 记录客户端是否连上
|
/// </summary>
|
public bool IsClientOn = false;
|
|
|
public SocketClient(TcpClient client, string ip, string port)
|
{
|
this.Client = client;
|
this.Ip = ip;
|
this.Port = ushort.Parse(port);
|
|
//绑定client事件
|
Client.OnConnect += new TcpClientEvent.OnConnectEventHandler(OnConnect);
|
Client.OnSend += new TcpClientEvent.OnSendEventHandler(OnSend);
|
Client.OnReceive += new TcpClientEvent.OnReceiveEventHandler(OnReceive);
|
Client.OnClose += new TcpClientEvent.OnCloseEventHandler(OnClose);
|
}
|
|
/// <summary>
|
/// 连接socket
|
/// </summary>
|
/// <returns>是否连接成功</returns>
|
public bool Connect()
|
{
|
|
return Client.Connetion(Ip, Port, false);
|
|
}
|
|
|
/// <summary>
|
/// 断开socket连接
|
/// </summary>
|
/// <returns>是否断开成功</returns>
|
public bool Disconnect()
|
{
|
return Client.Stop();
|
}
|
|
/// <summary>
|
/// 发送
|
/// </summary>
|
/// <param name="bytes"></param>
|
/// <returns></returns>
|
public virtual bool Send(byte[] bytes)
|
{
|
|
return Client.Send(bytes, bytes.Length);
|
}
|
|
|
/// <summary>
|
/// 关闭socket时执行的代码
|
/// </summary>
|
/// <param name="sender"></param>
|
/// <param name="enOperation"></param>
|
/// <param name="errorCode"></param>
|
/// <returns></returns>
|
protected abstract HandleResult OnClose(TcpClient sender, SocketOperation enOperation, int errorCode);
|
|
/// <summary>
|
/// 接收到报文时执行的代码
|
/// </summary>
|
/// <param name="sender"></param>
|
/// <param name="bytes">接收到的字符串</param>
|
/// <returns></returns>
|
protected abstract HandleResult OnReceive(TcpClient sender, byte[] bytes);
|
|
/// <summary>
|
/// 发送报文时执行的代码
|
/// </summary>
|
/// <param name="sender"></param>
|
/// <param name="bytes"></param>
|
/// <returns></returns>
|
protected abstract HandleResult OnSend(TcpClient sender, byte[] bytes);
|
|
|
/// <summary>
|
/// 连接客户端时执行的代码
|
/// </summary>
|
/// <param name="sender"></param>
|
/// <returns></returns>
|
protected abstract HandleResult OnConnect(TcpClient sender);
|
|
}
|
}
|