• C# Socket通讯


    服务器端

    class SocketServer
        {
            public static Socket mySocket;
            private static int port = 8885;   //端口  
            private static byte[] receive = new byte[1024];//接收的信息
            
    //private static byte[] send = new byte[1024];//发送的信息

            public static string receiveStr = "";

            public static void ServerMain()
            {

                //IPAddress ip = SocketServer.GetHostIP();

                IPAddress ip = SocketServer.GetHostIP();//IPAddress.Parse("127.0.0.1");
                mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                mySocket.Bind(new IPEndPoint(ip, port));//绑定IP地址:端口
                mySocket.Listen(5); //设定最多的连接请求为10个

                Thread myThread = new Thread(BeginListen);
                myThread.Start();


            }
            /// <summary>   
            
    /// 监听客户端连接   
            
    /// </summary> 
            public static void BeginListen()
            {
                while (true)
                {
                    //result = Encoding.ASCII.GetBytes(SocketServer.GetLiqLevel().ToString());
                    Socket clientSocket = mySocket.Accept();
                    clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));

                    Thread receiveThread = new Thread(ReceiveReq);
                    receiveThread.Start(clientSocket);
                }

            }

            //从客户端接收消息
            public static void ReceiveReq(object clientSociket)
            {
                
                while (true)
                {
                    Socket myclientSociket = (Socket)clientSociket;
                    try
                    {
                       int receiveNumber = myclientSociket.Receive(receive);

                       if (receiveNumber > 0)
                       {
                           receiveStr = Encoding.Default.GetString(receive);//接收到客户端的信息
                           MessageBox.Show(receiveStr, GlobalUserClass.strCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                           //IPAddress ip = SocketServer.GetHostIP();
                           
    //string ip = myclientSociket.RemoteEndPoint.ToString();
                           IPAddress ip = ((IPEndPoint)myclientSociket.RemoteEndPoint).Address;
                           
                           string sendMessage = "The Client's IP is:" + Convert.ToString(ip.ToString());//"这是返回你要查询的信息";
                           myclientSociket.Send(Encoding.Unicode.GetBytes(sendMessage));

                       }
                           

                    }
                    catch
                    {
                        //myclientSociket.Close();
                        return;
                    }
                }
            }

            //向客户端回馈信息
            public static void SendMessage()
            { 
            
            }
            public static IPAddress GetHostIP()
            {
                IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ip = ipe.AddressList[0];

                return ip;
            }
            
            /// <summary>
            
    /// 获取本地IP地址C#方法
            
    /// </summary>
            
    /// <returns></returns>
            private String GetIPAddress()
            {
                String str;
                String Result = "";
                String hostName = Dns.GetHostName();
                IPAddress[] myIP = Dns.GetHostAddresses(hostName);
                foreach (IPAddress address in myIP)
                {
                    str = address.ToString();
                    for (int i = 0; i < str.Length; i++)
                    {
                        if (str[i] >= '0' && str[i] <= '9' || str[i] == '.') Result = str;
                    }
                }
                return Result;
                
            }

        }

    客户端

           //从服务器端查询相关信息
            private void btnFind_Click(object sender, EventArgs e)
            {

                Thread.Sleep(1000);
                // 生成一个TCP/IP socket.
                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                SocketCliMain();

                //LiquidLevel = Convert.ToDouble(ReceiveData.ToString());
                
    //txtLiqLevel = LiquidLevel.ToString();

            }
            private static byte[] result = new byte[1024];
            private static byte[] Rece = new byte[1024];

            private void SocketCliMain()
            {

                int port = 8885;
                IPAddress ServeIP = IPAddress.Parse("127.0.0.1");//服务器的IP

                IPEndPoint remoteEP = new IPEndPoint(ServeIP, port);
                      Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    clientSocket.Connect(remoteEP);
                    //MessageBox.Show("连接服务器成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                catch
                { 
                    MessageBox.Show("与主站建立连接失败!""提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                //从服务器接收连接的应答信息   
                int receiveLength = 0;
                receiveLength = clientSocket.Receive(result);
                //string str = Encoding.Default.GetString(result);
                string strin = "";
                strin = Convert.ToString(Encoding.ASCII.GetString(result));//.Substring(0,receiveLength);


                if (receiveLength > 0)
                { 
                    //向服务器发送相关的数据信息
                    string sendMessage = "client send Message To Server";
                    clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                }
                if (receiveLength == 0)
                {
                    MessageBox.Show("连接服务器失败!""提示信息",  MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                int receiveNumber = 0;
                receiveNumber = clientSocket.Receive(Rece);
                string receiveString = "";
                bool flt = false;
                if (receiveNumber > 0)
                {
                    receiveString = Convert.ToString(Encoding.Unicode.GetString(Rece)); //Encoding.ASCII.GetString(result);
                    
    //receiveString = Encoding.Default.GetString(result);
                    flt = true;
                }
                if (receiveNumber == 0)
                {
                    MessageBox.Show("服务器传送数据失败!""提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                if (flt)
                {
                    MessageBox.Show(receiveString, "提示信息",MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    //clientSocket.Close();
                   
                }
  • 相关阅读:
    MapServer Tutorial——MapServer7.2.1教程学习——第一节:MapServer的基本配置管理,静态地图应用以及MapFile文件
    MapServer Tutorial——MapServer7.2.1教程学习——教程背景
    MapServer Tutorial——MapServer7.2.1教程学习(大纲)
    MapServer Configuring with IIS
    GDAL源码编译(32位)
    开机自启动相关程序
    异常:Invalid character found in the request target. The valid characters are defined in RFC 3986
    如何将解压版的tomcat设置为windows 服务启动
    修改Tomcat控制台标题
    Tomcat控制台中文乱码解决办法
  • 原文地址:https://www.cnblogs.com/lanshy/p/3067870.html
Copyright © 2020-2023  润新知