原文網址: http://www.cnblogs.com/csdev
Networkcomms 是一款C# 語言編寫的TCP/UDP通信框架 作者是英國人 以前是收費的 目前作者已經開源 開源地址是:https://github.com/MarcFletcher/NetworkComms.Net
這一節講一下,如何從服務器獲取列表數據
示例圖:
客戶單點擊 獲取數據 從服務器返回數據
客戶端代碼:
private void button4_Click(object sender, EventArgs e) { //GetUserList 是數據的請求消息類型 //ResUserList 是服務器端返回消息類型 當服務器返回ResUserList的數據時 客戶端自動對應獲取 IList<User> listUser = newTcpConnection.SendReceiveObject<string, IList<User>>("GetUserList", "ResUserList", 5000, "100"); BindData(listUser); } public void BindData(IList<User> theUsers) { listView1.Items.Clear(); listView1.Columns.Clear(); listView1.View = View.Details; //新增的 詳細方式 listView1.AllowColumnReorder = true; listView1.FullRowSelect = true; listView1.GridLines = true; listView1.Columns.Add("用戶ID", 100, HorizontalAlignment.Left); listView1.Columns.Add("用戶名", 100, HorizontalAlignment.Left); foreach (User theUser in theUsers) { ListViewItem li = new ListViewItem(); li.SubItems[0].Text = theUser.UserID.ToString(); li.SubItems.Add(theUser.Name); listView1.Items.Add(li); } }
服務器端代碼:
private void button1_Click(object sender, EventArgs e) { //IP地址和端口 IPEndPoint thePoint = new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text)); //開始監聽此IP和端口 使用TCP協議 Connection.StartListening(ConnectionType.TCP, thePoint); NetworkComms.AppendGlobalIncomingPacketHandler<string>("GetName", IncomingMsgHandle); NetworkComms.AppendGlobalIncomingPacketHandler<User>("UserLong", IncoingHandleLogin); NetworkComms.AppendGlobalIncomingPacketHandler<string>("GetUserList", IncoingHandleGetUserList); button1.Text = "已經開始監聽"; }
private void IncoingHandleGetUserList(PacketHeader header, Connection connection, string param) { //模擬一些數據 IList<User> userList=new List<User>(); User user1=new User (); user1.UserID="10000"; user1.Name="天涯共此時"; User user2=new User(); user2.UserID="20000"; user2.Name="海上生明月"; if (param == "100") { userList.Add(user1); userList.Add(user2); } else { userList.Add(user1); } connection.SendObject("ResUserList", userList); }
源碼下載:http://pan.baidu.com/s/1geXMSef