客户端从服务器获取一组IList<T>类型的数据非常常见(通常从数据库中获取)
我们用NeworkComms V3来演示一下(NetworkcommsV2.x版本也同样支持)
[ 使用protobuf.net序列化器]
第一步创建相关的工程文件:
MessageContract中的 User类为契约类,使用protobuf.net进行序列化
写法如下:
using System; using System.Collections.Generic; using System.Text; using ProtoBuf; namespace MessageContract { [ProtoContract] public class User { private string userID = string.Empty; private string name = string.Empty; public User() { } [ProtoMember(1)] public string UserID { get { return userID; } set { userID = value; } } [ProtoMember(2)] public string Name { get { return name; } set { name = value; } } } }
服务器端程序:
1、开始监听
//服务器开始监听客户端的请求 //开始监听某端口 Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text))); button1.Text = "监听中";
2、注册相应的处理器
NetworkComms.AppendGlobalIncomingPacketHandler<string>("ReqUsers", IncomingReqUsersHandle);
3、处理方法
private void IncomingReqUsersHandle(PacketHeader header, Connection connection, string msg) { try { //模拟一些数据 返回给客户端 IList<User> users = new List<User>(); User user1=new User (); user1.Name="名山大川"; user1.UserID="1000"; User user2=new User (); user2.Name="日月江河"; user2.UserID="2000"; users.Add(user1); users.Add(user2); connection.SendObject("ResUsers", users); } catch (Exception ex) { LogTools.LogException(ex, "IncomingMsgHandle"); } }
客户端代码:
1、连接服务器
connInfo = new ConnectionInfo(txtIP.Text, int.Parse(txtPort.Text)); //如果不成功,会弹出异常信息 newTcpConnection = TCPConnection.GetConnection(connInfo);
2、点击下图中的按钮,获取数据
private void button3_Click(object sender, EventArgs e) { IList<User> resMsg = newTcpConnection.SendReceiveObject<string, IList<User>>("ReqUsers", "ResUsers", 5000, "Test"); listBox2.DataSource = resMsg; listBox2.DisplayMember = "name"; listBox2.ValueMember = "name"; }
效果图如下:
www.networkcomms.cn编辑
相关的文章: