Пример #1
0
        static void Main(string[] args)
        {
            int port = 13145;

            NetClientProvider clientSocket = NetClientProvider.CreateProvider();

            //异步连接
            clientSocket.Connect(port, "127.0.0.1");
            clientSocket.ConnectedHandler = new OnConnectedHandler((sToken, isConnected) => {
                clientSocket.Send(Encoding.UTF8.GetBytes("client:hello" + DateTime.Now));
            });
            clientSocket.ReceiveOffsetHanlder = new OnReceiveOffsetHandler((sToken, buffer, offset, cnt) =>
            {
                Console.WriteLine("client:from server[" + Encoding.UTF8.GetString(buffer, offset, cnt));
            });

            //同步连接
            //if (clientSocket.ConnectSync(port, "127.0.0.1"))
            //{
            //    clientSocket.SendSync(Encoding.UTF8.GetBytes("I'm client" + DateTime.Now), (recCnt, buffer) =>
            //    {
            //        Console.WriteLine("client:from server[" + Encoding.UTF8.GetString(buffer, 0, recCnt));
            //    });
            //}
again:
            Console.WriteLine("输入内容发送(exist退出):");
            string key = Console.ReadLine();

            if (key != "exist")
            {
                clientSocket.Send(Encoding.UTF8.GetBytes("client:" + key + DateTime.Now));
                goto again;
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            int port = 13145;
            //服务端
            NetServerProvider serverSocket = NetServerProvider.CreateNetServerProvider();

            //已经截取接收到的真实数据
            serverSocket.ReceiveHanlder = new OnReceiveHandler((sToken, buffer) =>
            {
                Console.WriteLine("complate:from client[" + Encoding.UTF8.GetString(buffer));
                serverSocket.Send(sToken, Encoding.UTF8.GetBytes("hi" + DateTime.Now));
            });

            //直接返回缓冲区和接收到的偏移
            serverSocket.ReceiveOffsetHanlder = new OnReceiveOffsetHandler((sToken, buffer, offset, cnt) =>
            {
                byte[] dst = new byte[cnt];
                Array.Copy(buffer, offset, dst, 0, cnt);
                Console.WriteLine("offset:from client[" + Encoding.UTF8.GetString(dst));
            });

            bool isOk = serverSocket.Start(port);

            if (isOk)
            {
                Console.WriteLine("已启动服务。。。");

                //客户端
                NetClientProvider clientSocket = NetClientProvider.CreateNetClientProvider();
                clientSocket.ReceiveHanlder = new OnReceiveHandler((sToken, buffer) =>
                {
                    Console.WriteLine("client:from server[" + Encoding.UTF8.GetString(buffer));
                });
                clientSocket.Connect(port, "127.0.0.1");
                System.Threading.Thread.Sleep(1000);
                clientSocket.Send(Encoding.UTF8.GetBytes("hello" + DateTime.Now));
            }
            Console.ReadKey();
        }