码迷,mamicode.com
首页 > Windows程序 > 详细

使用C#中的Socket进行通讯

时间:2018-04-05 16:28:38      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:hello   tcp   res   while   utf8   UI   console   ddr   cli   

class Program
    {
        static void Main(string[] args)
        {
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            serverSocket.Bind(new IPEndPoint(IPAddress.Parse("10.6.0.38"), 88));

            serverSocket.Listen(19);

            serverSocket.BeginAccept(ClientAccept, serverSocket);
            Console.ReadLine();

        }
        static byte[] buffer = new byte[1024];
        static void ClientAccept(IAsyncResult ar)
        {


            Socket serverSocket = ar.AsyncState as Socket;

            Socket clientSocket = serverSocket.EndAccept(ar);

            clientSocket.Send(Encoding.UTF8.GetBytes("hellooo"));

            clientSocket.BeginReceive(buffer, 0, 1024, SocketFlags.None, ServerReceive, clientSocket);

            serverSocket.BeginAccept(ClientAccept, serverSocket);

        }

        static void ServerReceive(IAsyncResult ar)
        {
            Socket clientSOcket = ar.AsyncState as Socket;

            try
            {
                int len = clientSOcket.EndReceive(ar);
                if(len == 0)
                {
                    clientSOcket.Close();
                    return;
                }
                Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, len));

                clientSOcket.BeginReceive(buffer, 0, 1024, SocketFlags.None, ServerReceive, clientSOcket);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                clientSOcket.Close();
            }


            Console.ReadLine();
        }
    }

客户端

class Program
    {
        static void Main(string[] args)
        {
            byte[] buffer = new byte[1024];

            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            clientSocket.Connect(new IPEndPoint(IPAddress.Parse("10.6.0.38"), 88));

            int len = clientSocket.Receive(buffer, 0, 1024, SocketFlags.None);

            Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, len));

            while (true)
            {
                string temp = Console.ReadLine();

                if (temp == "c")
                {
                    clientSocket.Close();
                    return;
                }

                byte[] tempByte = Encoding.UTF8.GetBytes(temp);

                clientSocket.Send(tempByte);
            }

        }
    }

使用C#中的Socket进行通讯

标签:hello   tcp   res   while   utf8   UI   console   ddr   cli   

原文地址:https://www.cnblogs.com/what-lee/p/8722934.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!