[C#]手把手教你打造Socket的TCP通讯连接(四)

上一篇中,我们已经学会了服务器的代码,至此我们的SOcket的TCP通讯连接已经完成。这一篇我们总结一下。

服务器开启后,开始异步监听客户端连接。客户端连接时,实例化TCPListenerClient,并开始异步监听数据。接收到数据时,判断数据长度,0则为断开连接,不为0则引发接收数据完成事件。

可以通过TCPListenerClient发送数据或断开连接。

服务器关闭时要先断开所有客户端连接。

客户端连接服务器,开始异步接收服务器数据。接收到数据时,判断数据长度,0则为断开连接,不为0则引发接收数据完成事件。

客户端连接服务器后,可以发送数据与断开连接。

SocketHandler是专门处理接收发送的对象。

发送数据时,要判断发送队列是否有数据正在发送或等待发送。如果有数据,则把要发送的数据加入发送队列。

发送数据过程,先发送要发送数据的长度=>ushor类型=>byte[]类型。然后再发送主数据。

发送完成时,判断发送队列是否还有数据,有则继续发送。返回是否发送成功。遇到异常则不成功。

接收数据时,先接收byte[2]的主要数据长度头信息,转换为ushort类型。

然后接收这个长度的数据,EndRead里要判断是否接收完全,不完全则继续接收。

接收完成后直接返回接收到的数据。

 

下面发一个简易测试延迟程序的示例代码。

客户端。

View Code
namespace PingTesterClient
{
    class Program
    {

        static TCPClient client;
        static void Main(string[] args)
        {
            client = new TCPClient();
            client.ReceiveCompleted += Receive;
            Console.WriteLine("请输入IP地址:");
            client.Connect(new System.Net.IPEndPoint(IPAddress.Parse(Console.ReadLine()), 5000));

            byte[] data = BitConverter.GetBytes(DateTime.Now.TimeOfDay.TotalMilliseconds);
            client.SendAsync(data);

            Console.ReadLine();
        }

        private static void Receive(object sender, SocketEventArgs e)
        {
            Console.WriteLine(DateTime.Now.TimeOfDay.TotalMilliseconds - BitConverter.ToDouble(e.Data, 0));

            System.Threading.Thread.Sleep(100);
            byte[] data = BitConverter.GetBytes(DateTime.Now.TimeOfDay.TotalMilliseconds);
            client.SendAsync(data);
        }
    }
}

服务器。

View Code
namespace PingTesterServer
{
    class Program
    {
        static void Main(string[] args)
        {
            var listener = new TCPListener();
            listener.Port = 5000;
            listener.ReceiveCompleted += listener_ReceiveCompleted;
            listener.Start();

            Console.ReadLine();
        }

        static void listener_ReceiveCompleted(object sender, SocketEventArgs e)
        {
            e.Socket.SendAsync(e.Data);
        }
    }
}

客户端发送当前时间转byte[]数据

服务器接收到后又发送客户端发送的数据。

客户端收到数据后,用当前时间减去收到的时间,除以2,得到网络延迟。

 

项目文件:https://files.cnblogs.com/Kation/Wodsoft.Net.rar

 

原文地址:http://www.cnblogs.com/Kation/archive/2013/03/10/2952263.html

posted @ 2013-03-10 13:13  Kation  阅读(6521)  评论(28编辑  收藏  举报