1.下载
第一个是,SuperSocket的客户端 版本0.10.0
第二个是,SuperSocket提供的协议,过滤器 版本1.7.0.17


建立自己的过滤器
using SuperSocket.ProtoBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SuperSocketClient.SocketCore { /// /// 协议过滤 /// public class ReceiveFilter : BeginEndMarkReceiveFilter
//开头结尾 { //可选继承类: //TerminatorReceiveFilter //BeginEndMarkReceiveFilter //FixedHeaderReceiveFilter //FixedSizeReceiveFilter //CountSpliterReceiveFilter public ReceiveFilter() : base(Encoding.ASCII.GetBytes("#"), Encoding.ASCII.GetBytes("$\r\n")) { } ///
/// 经过过滤器,收到的字符串会到这个函数 /// ///
///
public override StringPackageInfo ResolvePackage(IBufferStream bufferStream) { return null; } } }
2、创建EasyClient实例,并使用前一步中创建的ReceiveFilter来初始化它。
using SuperSocket.ClientEngine; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; namespace SuperSocketClient.SocketCore { public class ClientAdmin { private EasyClient mClient; /// /// 构造函数 /// public ClientAdmin() { mClient = new EasyClient(); // Initialize the client with the receive filter and request handler mClient.Initialize(new ReceiveFilter(), (request) => { // handle the received request Console.WriteLine(request.Key); }); 连接断开事件 //mClient.Closed += ClientClosed; 收到服务器数据事件 //mClient.DataReceived += ClientDataReceived; 连接到服务器事件 //mClient.Connected += ClientConnected; 发生错误的处理 //mClient.Error += ClientError; } void ClientError(object sender, ErrorEventArgs e) { Console.WriteLine(e.Exception.Message); } void ClientConnected(object sender, EventArgs e) { Console.WriteLine("连接成功"); } void ClientDataReceived(object sender, DataEventArgs e) { string msg = Encoding.Default.GetString(e.Data); Console.WriteLine(msg); } void ClientClosed(object sender, EventArgs e) { Console.WriteLine("连接断开"); } /// /// 连接到服务器 /// /// IP地址 /// 端口 ///
连接成功返回真
public bool Connect(string strIP, int iPort) { // Connect to the server var rst = mClient.ConnectAsync(new IPEndPoint(IPAddress.Parse(strIP), iPort)); if (rst.Result) { return true; } else { return false; } } /// /// 连接到服务器 /// /// IP地址 /// 端口 ///
连接成功返回真
public bool Connect(string strIP, string strPort) { int iPort = Convert.ToInt32(strPort); return Connect(strIP, iPort); } /// /// 是否连接 /// ///
true表示连接
public bool IsConnected() { return mClient.IsConnected; } /// /// 向服务器发命令行协议的数据 /// /// 命令名称 /// 数据 public void SendCommand(string key, string data) { if (mClient.IsConnected) { byte[] arrBytes = Encoding.Default.GetBytes(string.Format("{0} {1}", key, data)); // Send data to the server mClient.Send(arrBytes); } else { throw new InvalidOperationException("断开连接"); } } } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/198599.html原文链接:https://javaforall.net
