示例代码参见 http://www.cnblogs.com/T-MAC/p/fastsocket-asyncbinary-usage.html
我这里只写一份客户端如何被动接收的代码。 先从AsyncBinarySocketClient继承定义一个客户端类,重载OnConnected,OnDisconnected,OnMessageReceived等方法。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using Sodao.FastSocket.SocketBase; using Sodao.FastSocket.Client; namespace MaxCode { public class MyClient : AsyncBinarySocketClient { public MyClient(int socketBufferSize, int messageBufferSize, int millisecondsSendTimeout, int millisecondsReceiveTimeout) : base(socketBufferSize, messageBufferSize, millisecondsSendTimeout, millisecondsReceiveTimeout) { } protected Encoding encode = Encoding.GetEncoding("utf-8"); protected override void OnMessageReceived(IConnection connection, MessageReceivedEventArgs e) { if(e.Buffer!=null && e.Buffer.Count>0) MessageBox.Show(encode.GetString(e.Buffer.Array)); base.OnMessageReceived(connection, e); } protected override void OnConnected(IConnection connection) { bConnected = true; base.OnConnected(connection); } protected override void OnDisconnected(IConnection connection, Exception ex) { bConnected = false; base.OnDisconnected(connection, ex); } private bool bConnected = false; public bool Connected { get { return bConnected; } } } }
然后在主程序中实例化本类
var client = new MaxCode.MyClient(8192, 8192, 3000, 3000); //注册服务器节点,这里可注册多个(name不能重复) client.RegisterServerNode("127.0.0.1:8401", new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 8401));
然后我们就可以通过重载的OnMessageReceived方法接收来自服务端的消息了。
希望对大家有所帮助。