我是靠谱客的博主 典雅鸡翅,最近开发中收集的这篇文章主要介绍C#建立简单的服务端和客户端通信,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1.服务端
(1) 创建服务端套接字
IPEndPoint ipe = new IPEndPoint(ip, port);
(2)创建服务端连接
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.stream, ProtocolType.tcp);
(3)绑定套接字
server.Bind(ipe);
(4) 监听 排队数量
server.listen(backlog)
(5)开始连接,接收数据, 给客户端应答
Thread my = new Thread(listenClientConnect);
my.Start();

 /// <summary>
    ///     最简单的服务端通讯
    /// </summary>
    public class NormalServerSocket
    {
        //端口和IP
        private int port = 6000;
        private string hostIp = "10.100.1.64";

        /// <summary>
        ///     创建服务套接字
        /// </summary>
        private Socket serverSocket = null;

        /// <summary>
        ///     这个连接 是服务接收到客户端连接 新建的连接
        /// </summary>
        private Socket clientSocket = null;

        /// <summary>
        ///     两个客户端连接作为实例
        /// </summary>
        private static Socket socketA = null;
        private static Socket socketB = null;


        string recStr = string.Empty;
        byte[] receiveByte = new byte[1024*100];

        /// <summary>
        ///     通信
        /// </summary>
        public void ServerCommunicate()
        {
            //创建一个服务端套接字
            IPAddress ip = IPAddress.Parse(hostIp);
            IPEndPoint ipe = new IPEndPoint(ip, port);
            //创建服务端连接
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //绑定套接字
            serverSocket.Bind(ipe);
            //监听,最大挂起连接队列
            serverSocket.Listen(1);

            //开始连接 接收数据 应答
            Thread myThread = new Thread(listenClientConnect);
            myThread.Start();

        }
        
        /// <summary>
        ///     客户端连接 接收数据
        /// </summary>
        private void listenClientConnect()
        {
            while (true)
            {
                clientSocket = serverSocket.Accept();
                //连接上后,应答
                clientSocket.Send(Encoding.Default.GetBytes("hello"));

                if (socketA == null)
                {
                    socketA = clientSocket;
                }
                else if(socketB == null)
                {
                    socketB = clientSocket;
                }
                else
                {
                    //其中一个断开
                    if(socketB.IsBound)
                    {
                        socketA = socketB;
                        socketB = clientSocket;
                    }
                    else
                    {
                        socketB = socketA;
                        socketA = clientSocket;
                    }
                }
                Thread recieveThread = new Thread(ReceiveMessage);
                recieveThread.Start(clientSocket);

            }
        }

        /// <summary>
        ///     接收数据
        /// </summary>
        /// <param name="clientSocket"></param>
        private void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while(true)
            {
                //接收数据到缓冲区
                int bytes = myClientSocket.Receive(receiveByte, receiveByte.Length, 0);
                //缓冲区的数据打印
                recStr += Encoding.Default.GetString(receiveByte, 0, bytes);
                try
                {
                    if (myClientSocket == socketA)
                    {
                        Console.Write("receive from A");
                        if (socketA != null && socketA.IsBound)
                        {
                            socketA.Send(receiveByte, 0, bytes, SocketFlags.None);
                        }
                        else
                        {
                            myClientSocket.Send(Encoding.ASCII.GetBytes("A is  not Connect Server!"));
                            Console.WriteLine("The ClientA dose not Connect to The Server");
                        }
                    }
                    else
                    {
                        Console.Write("receive from B");
                        if(socketB != null && socketB.IsBound)
                        {
                            socketB.Send(receiveByte, 0, bytes, SocketFlags.None);
                        }
                        else
                        {
                            myClientSocket.Send(Encoding.ASCII.GetBytes("B is  not Connect Server!"));
                            Console.WriteLine("The ClientB dose not Connect to The Server");
                        }
                    }
                }
                catch (Exception)
                {

                    throw;
                }
            }
        }
    }

2.客户端
(1) 创建连接
(2)Connect(ip,port);
(3) 接收数据
(4) 发送数据

/// <summary>
///     客户端通信
/// </summary>
public class ClientComm
{
    //端口和IP
    private int port = 6000;
    private string hostIp = "10.100.1.64";

    private static Socket clientSocket = null;

    private static byte[] recData = new byte[1024 * 8];

    /// <summary>
    ///     客户端通讯
    /// </summary>
    public void ClientCommunicate()
    {
        IPAddress ip = IPAddress.Parse(hostIp);
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //连接服务端
        try
        {
            clientSocket.Connect(ip, port);
            Console.WriteLine("连接成功!");
        }
        catch (Exception)
        {
            Console.WriteLine("连接失败!");
            return;
        }
        Thread th1 = new Thread(listenServer);
        th1.Start();
        Send();

    }

    /// <summary>
    ///     接收数据
    /// </summary>
    private void listenServer()
    {
        while(true)
        {
            int recLength = clientSocket.Receive(recData);
            Console.WriteLine("接收字节长度:" + recLength);
        }
    }

    /// <summary>
    ///     发送数据
    /// </summary>
    private void Send()
    {
        while (true)
        {
            try
            {
                Thread.Sleep(10000);
                string message = "你好,我测试客户端";
                byte[] mesByte = Encoding.Default.GetBytes(message);
                clientSocket.Send(mesByte);
            }
            catch (Exception ex)
            {
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
                break;
            }
        }
    }
}

`

最后

以上就是典雅鸡翅为你收集整理的C#建立简单的服务端和客户端通信的全部内容,希望文章能够帮你解决C#建立简单的服务端和客户端通信所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部