C# Socket 客户端服务端的创建、连接以及发送回复

最近简单学习了一下C# Socket的一些用法,在这里稍作总结;

了解过Socket的,应该都知道记可以做服务端开发也可以做客户端开发,在这里就简单介绍一下;

主要是客户端服务端的创建,连接,发送等内容;

做之前,先说一下这个结构,我们需要连接,发送等逻辑,为了方便测试,我们需要建两个项目;

建两个控制台应用程序,一个服务端,一个客户端;

首先,我们在服务端项目中建一个Server.cs;

引入需要的程序集; 

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
    public class Server {
        private string m_host;
        private int m_port;
        private int m_backlog;
        private Socket m_socket;

        /// 
        /// 传入参数默认加入数量限制参数
        /// 
        /// 
        /// 
        public Server(string host, int port) : this(host, port, 10) {
            
        }

        /// 
        /// 创建一个server对象
        /// 
        /// ip地址
        /// 端口号
        /// 连接数量
        public Server(string host, int port, int backlog) {
            m_host = host;
            m_port = port;
            m_backlog = backlog;
            m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        /// 
        /// 开启服务器
        /// 之后开启一个后台运行的线程, 用于监听客户端的请求
        /// 
        public void Begin() {
            m_socket.Bind(new IPEndPoint(IPAddress.Parse(m_host), m_port));
            m_socket.Listen(m_backlog);
            Console.WriteLine("Server Begin Success");

            Thread thread = new Thread(Accept);
            thread.IsBackground = true;
            thread.Start();
        }

        /// 
        /// 监听客户端的连接,并打印出客户端的Ip等相关信息
        /// 同时在开启一个后台线程用于监听客户端向服务端发送的信息并接收
        /// 
        private void Accept() {
            //接受客户端的方法,会挂起当前线程
            Socket client = m_socket.Accept();
            IPEndPoint point = client.RemoteEndPoint as IPEndPoint;
            Console.WriteLine(point.Address + " - " + point.Port + " - 连接成功;");

            Thread thread = new Thread(Receive);
            thread.IsBackground = true;
            thread.Start(client);

            Accept();
        }

        /// 
        /// 处理接收来自客户端发过来的信息,同时向当前客户端回复信息
        /// 在这里采用UTF8编码格式,客户端服务端要统一,否则发送与接收过程会出现编码问题
        /// 
        /// 当前客户端对象
        private void Receive(object obj) {
            var client = obj as Socket;
            IPEndPoint point = client.RemoteEndPoint as IPEndPoint;
            try {
                byte[] msg = new byte[1024];
                var len = client.Receive(msg);
                string msgStr = Encoding.UTF8.GetString(msg, 0, len);
                Console.WriteLine(point.Address + ":    " + msgStr);
                client.Send(Encoding.UTF8.GetBytes("回应:   " + msgStr));

                Receive(client);
            } catch {
                Console.WriteLine(point.Address + ":    客户端已断开连接");
            }
            
        }
    }

然后我们在Main(string[] args)中调用;

    static void Main(string[] args) {
        string ip = "***.***.***.***";
        int port = 12312;
        Server.Server server = new Server.Server(ip, port);
        server.Begin();
        Console.ReadLine();
    }

点击运行,这样,我们的服务器就跑起来了;

C# Socket 客户端服务端的创建、连接以及发送回复_第1张图片

下面我们来在客户端项目中创建Client.cs;

引入必要的程序集;

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
    public class Client {

        private const int TIME_OUT = 3000;

        private string m_host;
        private int m_port;
        private Socket m_socket;

        /// 
        /// 创建一个客户端对象
        /// 
        /// ip地址
        /// 对应端口号
        public Client(string host, int port) {
            m_host = host;
            m_port = port;
            m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        /// 
        /// 判断当前是否有效连接
        /// 
        /// 
        public bool IsConnect() {
            return m_socket != null && m_socket.Connected;
        }

        /// 
        /// 开始连接服务器,设置超时时间(测试方便使用)
        /// 连接结束后,开启一个后台线程用于监听接收服务端的发来的消息
        /// 
        public void Connect() {
            Thread thread = new Thread(() => {
                IAsyncResult asyncResult = m_socket.BeginConnect(new IPEndPoint(IPAddress.Parse(m_host), m_port), null, null);
                int time = 0;
                while(time < TIME_OUT && !asyncResult.IsCompleted) {
                    Thread.Sleep(100);
                    time += 100;
                    Console.WriteLine("Connecting ...");
                }
                if(asyncResult.IsCompleted) {
                    if(time >= TIME_OUT) {
                        //todo:超时
                        Console.WriteLine("Client Connect Timeout");
                    } else {
                        if(IsConnect()) {
                            Console.WriteLine("Client Connect Success");
                        } else {
                            Console.WriteLine("Client Connect Faile");
                        }
                    }
                }

                Thread t = new Thread(Receive);
                t.IsBackground = true;
                t.Start();
            });
            thread.Start();
        }

        /// 
        /// 当前连接有效的情况下,向服务端发送信息(UTF8)
        /// 
        /// 
        public void Send(string msg) {
            if(!IsConnect()) {
                Console.WriteLine("Client Connect Faile");
                return;
            }
            var msgByte = Encoding.UTF8.GetBytes(msg);
            m_socket.Send(msgByte);
        }

        /// 
        /// 处理服务器发过来的信息(UTF8)
        /// 
        private void Receive() {
            while(true) {
                try{
                    byte[] msg = new byte[1024];
                    int len = m_socket.Receive(msg);
                    Console.WriteLine("Server:" + Encoding.UTF8.GetString(msg, 0, len));

                    Receive();
                }
                catch{
                    Console.WriteLine("服务端连接无效");
                    break;
                }
            }
            
        }
    }

创建好之后,我们把客户端也开起来;

    static void Main(string[] args) {
        string ip = "***.***.***.***";
        int port = 12312;
        Client.Client client = new Client.Client(ip, port);
        client.Connect();

        Console.WriteLine("Please input message:");
        string msg = Console.ReadLine();
        while(msg != "quit") {
            if(msg != "") {
                client.Send(msg);
            } else {
                Console.WriteLine("This is Empty");
            }
            msg = Console.ReadLine();
        }

        Console.ReadLine();
    }

C# Socket 客户端服务端的创建、连接以及发送回复_第2张图片

下面我们进行测试:

C# Socket 客户端服务端的创建、连接以及发送回复_第3张图片

本文为原创作品,如有雷同,纯属巧合;

文中若有不当之处,欢迎指正,共同学习,谢谢;

你可能感兴趣的:(C#语言,C#,Socket)