使用TcpServerBase构建服务器
描述
TcpServerBase是从TcpServerBase<DataEventArgs>派生面来,它只能简单的接受客户端连接、接收客户端发来的数据、向客户端发送byte[]数据,但它能保证数据的正常收发,同时维护连接的客户端的实例,TcpServerBase是使用事件驱动,当收到客户端发送过来的数据后,通过OnRecvComplete事件将数据取出,事件的第一个参数sender是触发的客户端对象,为SocketAsync<DataEventArgs>类形。
构建服务器
新建工程ServerBase,引用NetworkSocket.dll,引入NetworkSocket命名空间
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NetWorkSocket; using System.Net; namespace ServerBase { class Program { // 服务实例 static TcpServerBase server = new TcpServerBase(); static void Main(string[] args) { // 绑定接收数据事件 server.OnRecvComplete += new EventHandler<DataEventArgs>(server_OnRecvComplete); // 绑定客户端连接事件 server.OnConnect += new EventHandler(server_OnConnect); // 启动服务 server.StartListen(new IPEndPoint(IPAddress.Any, 8181)); while (true) { Console.ReadLine(); } } /// <summary> /// 客户端连接事件 /// </summary> /// <param name="sender">客户端</param> /// <param name="e">事件</param> static void server_OnConnect(object sender, EventArgs e) { var client = sender as SocketAsync<DataEventArgs>; Console.WriteLine("{0}连接进来...当前连接数:{1}", client.RemoteEndPoint, server.AliveClients.Count); } /// <summary> /// 接收数据完成事件 /// </summary> /// <param name="sender">客户端</param> /// <param name="e"></param> static void server_OnRecvComplete(object sender, DataEventArgs e) { // sender就是当前发来数据的客户端 var client = sender as SocketAsync<DataEventArgs>; // 将数据转为文本 string msg = Encoding.UTF8.GetString(e.Binary.Buffer); // 输出消息 Console.WriteLine("{0}: {1}", client.RemoteEndPoint, msg); msg = "这是来自服务器的消息..."; var data = Encoding.UTF8.GetBytes(msg); client.Send(data); } } }
构建客户端
新建工程ClientBase,引用NetworkSocket.dll,引入NetworkSocket命名空间
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NetWorkSocket; using System.Net; namespace ClientBase { class Program { // 客户端实例 static TcpClientBase client = new TcpClientBase(); static void Main(string[] args) { // 绑定接收数据事件 client.OnRecvComplete += new EventHandler<DataEventArgs>(client_OnRecvComplete); // 连接到服务器 bool state = client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8181)); if (state == true) { while (true) { string msg = Console.ReadLine(); var data = Encoding.UTF8.GetBytes(msg); client.Send(data); } } } /// <summary> /// 收到服务器发来数据事件 /// </summary> /// <param name="sender">本客户端</param> /// <param name="e">事件</param> static void client_OnRecvComplete(object sender, DataEventArgs e) { // 将数据转为文本 string msg = Encoding.UTF8.GetString(e.Binary.Buffer); // 输出消息 Console.WriteLine("收到: {0}", msg); } } }
运行效果