static void sendMsg() { //发送的消息 try { Console.ReadKey(); NetModel item = new NetModel() { ID = 1, Commit = "LanOu", Message = "Unity" }; //序列化对象 byte[] temp = Serialize(item); //ProtoBuf的优势一:小 Console.WriteLine(temp.Length); //反序列化为对象 NetModel result = DeSerialize <NetModel>(temp, temp.Length); Console.WriteLine(result.Message); //调用客户端套接字发送字节数组 socketclient.Send(temp); //将发送的信息追加到聊天内容文本框中 Debug.WriteLine("hello...." + ": " + GetCurrentTime() + "\r\n" + "\r\n\n"); //调用ClientSendMsg方法 将文本框中输入的信息发送给服务端 } catch (Exception ex) { Debug.WriteLine("远程服务器已经中断连接" + "\r\n\n"); } }
public static void Main(string[] args) { // Serialize<TestDataTable>(); NetModel item = new NetModel() { ID = 1, Commit = "LanOu", Message = "Unity" }; NetModel item2 = new NetModel() { ID = 2, Commit = "2f", Message = "2msg" }; TestDataTable tb = new TestDataTable(); NetModel[] items = { item, item2 }; tb.Data = items; byte[] dtb = Serialize <TestDataTable>(tb); TestDataTable tb2 = new TestDataTable(); tb2 = DeSerialize <TestDataTable>(dtb, dtb.Length); //定义一个套接字监听 socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //获取文本框中的IP地址 IPAddress address = IPAddress.Parse("127.0.0.1"); //将获取的IP地址和端口号绑定在网络节点上 IPEndPoint point = new IPEndPoint(address, 8098); //客户端套接字连接到网络节点上,用的是Connect socketclient.Connect(point); //线程 threadclient = new Thread(recvMsg); threadclient.IsBackground = true; threadclient.Start(); //不停的给服务器发送数据 while (true) { sendMsg(); } }
// 接收服务端发来信息的方法 static void recvMsg() { //持续监听服务端发来的消息 while (true) { try { //定义一个1M的内存缓冲区,用于临时性存储接收到的消息 byte[] arrRecvmsg = new byte[1024]; //将客户端套接字接收到的数据存入内存缓冲区,并获取长度 int length = socketclient.Receive(arrRecvmsg); NetModel netModel = DeSerialize <NetModel>(arrRecvmsg, length); //接受的消息 Console.WriteLine("服务器:" + GetCurrentTime() + "\r\n" + netModel.Message + "\r\n\n"); } catch (Exception ex) { Debug.WriteLine("远程服务器已经中断连接" + "\r\n\n"); break; } } }