• C# Socket 简单的控制台案例


    一、服务器端

    1. 实例化并设置socket实例对象

        a.创建ip地址和端口

        b.绑定监听地址

        c.设置一下允许同时访问数

    2. 监听连接

        a.通过启动一个新的线程执行,这样主线程不会假死(启动线程,所带的参数必须是object类型)

        b.利用循环等待连接并返回一个负责通信的socket实例

        c.返回的socket实例中可以获取到所连接客服的IP地址

    3. 接收客服的发送过来的消息

        a.在监听方法中启动一个新的线程执行

        b.利用循环获取发送过来的消息,调用获取消息的方法需要传递一个字节变量参数,作为容器。方法返回值为int,表示获取到的有效字节数

        c.如果有效字节数为0则跳出循环

        d.接收到消息给客服的返回消息

    4. 控制台程序服务器端代码

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    
    namespace ServerSocket
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
                Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Any;
                IPEndPoint point = new IPEndPoint(ip, 2333);
                //socket绑定监听地址
                serverSocket.Bind(point);
                Console.WriteLine("Listen Success");
                //设置同时连接个数
                serverSocket.Listen(10);
    
                //利用线程后台执行监听,否则程序会假死
                Thread thread = new Thread(Listen);
                thread.IsBackground = true;
                thread.Start(serverSocket);
    
                Console.Read();
            }
    
            /// <summary>
            /// 监听连接
            /// </summary>
            /// <param name="o"></param>
            static void Listen(object o)
            {
                var serverSocket = o as Socket;
                while (true)
                {
                    //等待连接并且创建一个负责通讯的socket
                    var send = serverSocket.Accept();
                    //获取链接的IP地址
                    var sendIpoint = send.RemoteEndPoint.ToString();
                    Console.WriteLine($"{sendIpoint}Connection");
                    //开启一个新线程不停接收消息
                    Thread thread = new Thread(Recive);
                    thread.IsBackground = true;
                    thread.Start(send);
                }
            }
    
            /// <summary>
            /// 接收消息
            /// </summary>
            /// <param name="o"></param>
            static void Recive(object o)
            {
                var send = o as Socket;
                while (true)
                {
                    //获取发送过来的消息容器
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    var effective = send.Receive(buffer);
                    //有效字节为0则跳过
                    if (effective == 0)
                    {
                        break;
                    }
                    var str = Encoding.UTF8.GetString(buffer,0, effective);
                    Console.WriteLine(str);

               var buffers = Encoding.UTF8.GetBytes("Server Return Message");
               send.Send(buffers);

                }
            }
        }
    }

    二、客户端

    1. 实例化并进行连接socket实例对象

        a.创建ip地址和端口(服务器的IP和端口)

        b.与服务器端建立链接

    2. 接收服务器发送的消息

        a.启动一个新的线程执行

        b.利用循环获取发送过来的消息,调用获取消息的方法需要传递一个字节变量参数,作为容器。方法返回值为int,表示获取到的有效字节数

        c.如果有效字节数为0则跳出循环

    3. 给服务器发送消息

        a. 调用socket对象的send()方法直接发送

    4. 控制台程序客户端代码

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    
    namespace SocketClient
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
                //创建实例
                Socket socketClient = new Socket(SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse("192.168.0.111");
                IPEndPoint point = new IPEndPoint(ip, 2333);
                //进行连接
                socketClient.Connect(point);
                
                //不停的接收服务器端发送的消息
                Thread thread = new Thread(Recive);
                thread.IsBackground = true;
                thread.Start(socketClient);
    
                //不停的给服务器发送数据
                int i = 0;
                while (true)
                {
                    i++;
                    var buffter = Encoding.UTF8.GetBytes($"Test Send Message:{i}");
                    var temp = socketClient.Send(buffter);
                    Thread.Sleep(1000);
                }
                
            }
    
    
            /// <summary>
            /// 接收消息
            /// </summary>
            /// <param name="o"></param>
            static void Recive(object o)
            {
                var send = o as Socket;
                while (true)
                {
                    //获取发送过来的消息
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    var effective = send.Receive(buffer);
                    if (effective == 0)
                    {
                        break;
                    }
                    var str = Encoding.UTF8.GetString(buffer, 0, effective);
                    Console.WriteLine(str);
                }
            }
        }
    }
  • 相关阅读:
    How many ways
    HDOj-1016 Prime Ring Problem
    DHU-1241 Oil Deposits
    Red and Black
    HDU-3790 最短路径问题
    vim/Gvim配置
    lintcode431- Connected Component in Undirected Graph- medium
    lintcode120- Word Ladder- medium
    lintcode531- Six Degrees- medium- microsoft
    lintcode624- Remove Substrings- medium
  • 原文地址:https://www.cnblogs.com/haosit/p/6813583.html
Copyright © 2020-2023  润新知