当前位置:   article > 正文

C# Socket发送请求及监听_c# seriport持续监听

c# seriport持续监听

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketTest
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        /// 
        [STAThread]
        static void Main ()
        {
            // string sendMsg = "hello word !";//需要发送的数据
             MD5 md5 = new MD5CryptoServiceProvider ();
            byte[] data = System.Text.Encoding.UTF8.GetBytes (sendMsg);
            byte[] result = md5.ComputeHash (data);  //md5加密数据
            String strReturn = String.Empty;
            for (int i = 0; i < result.Length; i++)
                strReturn += result[i].ToString ("x").PadLeft (2,'0');
            sendMsg = sendMsg + "|" + strReturn;
            Console.WriteLine ("发送的内容:" + sendMsg);
            int len = Encoding.UTF8.GetByteCount (sendMsg);
            string sLen = ("" + len).PadLeft (4,'0');
            //将长度插入信息头中
            sendMsg = sLen + sendMsg;
            Console.WriteLine (sendMsg);
            string ipadd = "127.0.0.1";//设置自己连接的IP地址
            IPEndPoint ie = new IPEndPoint (IPAddress.Parse (ipadd),8080); // 服务器的IP和端口
            Socket server = new Socket (AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            server.Connect (ie);
            server.Send (Encoding.Default.GetBytes (sendMsg));
             byte[] buffer = new byte[1024 * 1024];
             int n = server.Receive (buffer);//socket是连接服务器的
             //读取服务端发来的消息
             string msg = Encoding.UTF8.GetString (buffer,0,n);
             Console.WriteLine ("请求返回信息:" + msg);
            server.Close ();
            startListening ();
            destory ();
           
        }


        /*
         *  1、打开服务端端口
         *  2、开始监听客户端Socket连接,并获取客户端Socket
         *  3、将客户端Socket保存到Hashtable中,并处理客服端Socket发送的数据
         */

        private static TcpListener listener = null;
        private static void startListening ()
        {
            //打开服务端端口
            IPAddress lip = IPAddress.Parse ("127.0.0.1");
            listener = new TcpListener (lip,12345);
            listener.Start ();
            while (true)
            {
                Socket socket = null;
                try
                {
                    //开始监听客户端Socket
                    socket = listener.AcceptSocket ();
                   // string clientIP = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString ();
                   // string serverIP = ((IPEndPoint)socket.LocalEndPoint).Address.ToString ();
                    //检查是否是局域网访问,若不是是局域网访问则终止。
                 
                        socket.SendTimeout = 30 * 1000;
                        //生成客服端Socket处理数据,并将客户端Socket保存到Hashtable中
                        //获取信息头,信息体长度
                        Byte[] buf_len = new Byte[4];
                        socket.Receive (buf_len);
                        string str_len = UTF8Encoding.UTF8.GetString (buf_len);
                        int len = Int32.Parse (str_len);
                        //根据信息头长度,获取信息体内容
                        Byte[] buffer = new Byte[len];
                        socket.Receive (buffer);
                        string msg = UTF8Encoding.UTF8.GetString (buffer);
                        Console.WriteLine ("回调地址接受信息=="+msg);
                        if (socket != null)
                        {
                            socket.Close ();
                            socket = null;
                        }
                }
                catch (Exception e)
                {
                    Console.WriteLine (e.ToString ());
                }
            }
        }

        /*
         * 销毁监听线程
         */
        public static void destory ()
        {
            if (listener != null)
            {
                listener.Stop ();
                listener = null;
            }
         
        }
    }
}

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号