• socket 服务器浏览器与服务器客户端实例


    一、服务器与浏览器

    // 取得本机的loopback网络地址,即127.0.0.1
                IPAddress address = IPAddress.Loopback;
                IPEndPoint endPoint = new IPEndPoint(address, 49152);
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Bind(endPoint);
                socket.Listen(10);
                Console.WriteLine("开始监听,端口号;{0}.", endPoint.Port);
                while (true)
                {
                    Socket client = socket.Accept();
                    Console.WriteLine(client.RemoteEndPoint);
                    byte[] buffer = new byte[4096];
                    int length = client.Receive(buffer, 4096, SocketFlags.None);
                    System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
                    string requestString = utf8.GetString(buffer, 0, length);
                    Console.WriteLine(requestString);
                    string statusLine = "HTTP/1.1 200 OK\r\n";
                    byte[] statusLineBytes = utf8.GetBytes(statusLine);
                    string responseBody = "<html><head><title>From Socket Server</title></head><body><hl>Hello,world.</hl></body></html>";
                    byte[] responseBodyBytes = utf8.GetBytes(responseBody);
                    // 回应的头部
                    string responseHeader = string.Format("Content-Type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n",
                        responseBody.Length);
                    byte[] responseHeaderBytes = utf8.GetBytes(responseHeader);
                    // 向客户端发送状态消息
                    client.Send(statusLineBytes);
                    // 向客户端发送回应头
                    client.Send(responseHeaderBytes);
                    client.Send(new byte[] { 13, 10 });
                    client.Send(responseBodyBytes);
                    client.Close();
                    if (Console.KeyAvailable)
                    {
                        break;
                    }
                    socket.Close();
                }

    最后在浏览器地址栏中输入:http://localhost:49152

    二、服务器客户端

    服务端:

    class Program
        {
            private static byte[] result = new byte[1024];
            private static int myProt = 8885;   //端口
            static Socket serverSocket;
            static void Main(string[] args)
            {
                //服务器IP地址
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址:端口
                serverSocket.Listen(10);    //设定最多10个排队连接请求
                Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
                //通过Clientsoket发送数据
                Thread myThread = new Thread(ListenClientConnect);
                myThread.Start();
                Console.ReadLine();
            }
    
            /// <summary>
            /// 监听客户端连接
            /// </summary>
            private static void ListenClientConnect()
            {
                while (true)
                {
                    Socket clientSocket = serverSocket.Accept();
                    clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
                    Thread receiveThread = new Thread(ReceiveMessage);
                    receiveThread.Start(clientSocket);
                }
            }
    
            /// <summary>
            /// 接收消息
            /// </summary>
            /// <param name="clientSocket"></param>
            private static void ReceiveMessage(object clientSocket)
            {
                Socket myClientSocket = (Socket)clientSocket;
                while (true)
                {
                    try
                    {
                        //通过clientSocket接收数据
                        int receiveNumber = myClientSocket.Receive(result);
                        Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        myClientSocket.Shutdown(SocketShutdown.Both);
                        myClientSocket.Close();
                        break;
                    }
                }
            }
        }

    客户端:

    class Program
        {
            private static byte[] result = new byte[1024];
            static void Main(string[] args)
            {
                //设定服务器IP地址
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    clientSocket.Connect(new IPEndPoint(ip, 8885)); //配置服务器IP与端口
                    Console.WriteLine("连接服务器成功");
                }
                catch
                {
                    Console.WriteLine("连接服务器失败,请按回车键退出!");
                    return;
                }
                //通过clientSocket接收数据
                int receiveLength = clientSocket.Receive(result);
                Console.WriteLine("接收服务器消息:{0}",Encoding.ASCII.GetString(result,0,receiveLength));
                //通过 clientSocket 发送数据
                for (int i = 0; i < 10; i++)
                {
                    try
                    {
                        Thread.Sleep(1000);    //等待1秒钟
                        string sendMessage = "client send Message Hellp" + DateTime.Now;
                        clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                        Console.WriteLine("向服务器发送消息:{0}" + sendMessage);
                    }
                    catch
                    {
                        clientSocket.Shutdown(SocketShutdown.Both);
                        clientSocket.Close();
                        break;
                    }
                }
                Console.WriteLine("发送完毕,按回车键退出");
                Console.ReadLine();
            }
        }
  • 相关阅读:
    Redis
    Maven总结
    spring知识点总结
    网上好文搜集整理
    python 代码删除空目录
    plantUML使用指南
    python的基础操作
    八卦基础编程学习
    python历年入坑记录大全
    python实现的百度云自动下载
  • 原文地址:https://www.cnblogs.com/honghong75042/p/3072377.html
Copyright © 2020-2023  润新知