C# superSocket client客户端简单示例

本教程是c# 的控制台程序,C# superSocket client客户端工具。

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace superSocketClient
{
    class Program
    {
        static Socket socketClient { get; set; }
        static void Main(string[] args)
        {
            //创建实例
            socketClient = new Socket(SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse("192.168.0.121");
            IPEndPoint point = new IPEndPoint(ip, 2012);
            //进行连接
            socketClient.Connect(point);


            //不停的接收服务器端发送的消息
            Thread thread = new Thread(Recive);
            thread.IsBackground = true;
            thread.Start();


            ////不停的给服务器发送数据
            Thread thread2 = new Thread(Send);
            thread2.IsBackground = true;
            thread2.Start();

            Console.ReadKey();
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="o"></param>
        static void Recive()
        {
          //  为什么用telnet客户端可以,但这个就不行。
            while (true)
            {
                //获取发送过来的消息
                byte[] buffer = new byte[1024 * 1024 * 2];
                var effective = socketClient.Receive(buffer);
                if (effective == 0)
                {
                    break;
                }
                var str = Encoding.UTF8.GetString(buffer, 0, effective);
                Console.WriteLine("来自服务器 --- " + str);
                Thread.Sleep(2000);
            }
        }


        static void Send()
        {          
            int i = 0;
            int sum = 0;
            while (true)
            {
                i++;
                sum += i;
                var buffter = Encoding.UTF8.GetBytes($"ADD {sum} {sum + 1}" + "\r\n");
                var temp = socketClient.Send(buffter);
                Console.WriteLine(i);
                Thread.Sleep(1000);
            }

        }
    }
}

以上代码可直接运行,客户端与服务器可以互发消息。 
注意这只是一个基本应用,如果需要企业级的,高级一些的应用,则需要 
自写 Session、Server,需要继承CommandBase和重载ExecuteCommand。 

相关教程

supersocket例子 c#的Websocket server和web client

supersocket server c# 教程

本站原创,未经允许不得转载:lingkb » C# superSocket client客户端简单示例
赞(0)

评论抢沙发