c#实现socket通信(一个服务器端对应多个客户端)

之前我写过一个一对一的通信 如果有需要可以参考
一对一地址
这次的一对多其实也就是加了个异步处理

服务器端:

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

namespace JungleWars
{
    class Program
    {
        static void Main(string[] args)
        {
            StartServerAsync();
            Console.ReadKey();
        }
        static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//地址类型,流,协议类型
                                                                                                          //192.168.43.76 本机ip:127.0.0.1
        static void StartServerAsync()//异步
        {
           

            IPAddress ipaddress = IPAddress.Parse("192.168.43.76");
            IPEndPoint ipendpoint = new IPEndPoint(ipaddress, 8000);

            serverSocket.Bind(ipendpoint);//绑定完成

            serverSocket.Listen(10);//处理链接队列个数 为0则为不限制


            //Socket clientSocket = serverSocket.Accept();//接收一个客户端链接
            serverSocket.BeginAccept(AcceptCallBack, serverSocket);
        }

        static  byte[] dateBuffer = new byte[1024];

        static void AcceptCallBack(IAsyncResult ar)
        {
            Socket serversocket = ar.AsyncState as Socket;
            Socket clientSocket = serversocket.EndAccept(ar);
            ///向客户端发送一条消息
            string msg = "你好呀 客户端!";
            byte[] date = System.Text.Encoding.UTF8.GetBytes(msg);//转换成为bytes数组
            clientSocket.Send(date);
            clientSocket.BeginReceive(dateBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket);

            serverSocket.BeginAccept(AcceptCallBack, serverSocket);
        }
        static void ReceiveCallBack(IAsyncResult ar)
        {
            Socket clientSocket = null;
            try
            {
                clientSocket = ar.AsyncState as Socket;
                int count = clientSocket.EndReceive(ar);
                if (count == 0)
                {
                    clientSocket.Close();
                    return;

                }
                string msg = Encoding.UTF8.GetString(dateBuffer, 0, count);
                Console.WriteLine("接收数据:" + msg);
                clientSocket.BeginReceive(dateBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket);//回调
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
                if (clientSocket != null)
                {
                    clientSocket.Close();
                }
            }
        }
        static void StartServerSync()
        {
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//地址类型,流,协议类型
                                                                                                              //192.168.43.76 本机ip:127.0.0.1

            IPAddress ipaddress = IPAddress.Parse("192.168.43.76");
            IPEndPoint ipendpoint = new IPEndPoint(ipaddress, 8000);

            serverSocket.Bind(ipendpoint);//绑定完成

            serverSocket.Listen(10);//处理链接队列个数 为0则为不限制


            Socket clientSocket = serverSocket.Accept();//接收一个客户端链接

            ///向客户端发送一条消息
            string msg = "你好呀 客户端!";
            byte[] date = System.Text.Encoding.UTF8.GetBytes(msg);//转换成为bytes数组
            clientSocket.Send(date);

            ///接收一条客户端的消息
            byte[] dateBuffer = new byte[1024];
            int count = clientSocket.Receive(dateBuffer);

            string msgReceive = System.Text.Encoding.UTF8.GetString(dateBuffer, 0, count);
            Console.WriteLine(msgReceive);

            Console.ReadKey();

            clientSocket.Close();
            serverSocket.Close();
        }//同步
    }
    
}

客户端:

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

namespace Tcp客户端
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(new IPEndPoint(IPAddress.Parse("192.168.43.76"), 8000));

            byte[] date = new byte[1024];
            int count = clientSocket.Receive(date);
            string msg = Encoding.UTF8.GetString(date, 0, count);
            Console.WriteLine(msg);

          

            while (true)
            {
                string s = Console.ReadLine();
                clientSocket.Send(Encoding.UTF8.GetBytes(s));
            }

            //Console.ReadKey();
            //clientSocket.Close();
        }
    }
}

我们可以在文件中找到我们的客户端 之后发送 消息之后
就可以在服务器端接收到

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值