如何重用客户端套接字连接? [英] How to reuse client Socket connection?

查看:114
本文介绍了如何重用客户端套接字连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        static existech sa;
        static void Main(string[] args)
        {
            string path = @"StringReturn.txt";
            string serverIP;
            string serverPORT;
                serverIP = "172.16.7.123";
                serverPORT = "1818";

           
                Console.WriteLine(serverIP);
                socklan(serverIP, serverPORT);

           Start:
            try
            {
                        Thread.Sleep(2000);
                        sa.writeLine("*HAND:ID?");
                        string reID = sa.readLine();
                        DateTime now = DateTimeNowCache.GetDateTime();
                        Console.WriteLine(now);
                        Console.WriteLine(reID);
   using (StreamWriter file = new StreamWriter(path, true))
                {
                    file.WriteLine(reID);
                    file.Close();
                }


                    Console.WriteLine();
                Thread.Sleep(2000);
                        sa.writeLine("*HAND:STAT?");
                        string reSTAT = sa.readLine();
            DateTime now1 = DateTimeNowCache.GetDateTime();
                        Console.WriteLine(now1);
                        Console.WriteLine(reSTAT);
                                using (StreamWriter file = new StreamWriter(path, true))
                {
                    file.WriteLine(reSTAT);
                    file.Close();
                }

                       Thread.Sleep(2000);
                        sa.writeLine("*HAND:PROF?");
                        string rePROF = sa.readLine();
      DateTime now2 = DateTimeNowCache.GetDateTime();
                        Console.WriteLine(now2);
                        Console.WriteLine(rePROF);
      using (StreamWriter file = new StreamWriter(path, true))
                {
                    file.WriteLine(rePROF);
                    file.Close();
                }

                Console.WriteLine();
                Thread.Sleep(2000);
                sa.writeLine("*HAND:YIELD?");
                string reYIELD = sa.readLine();
   DateTime now3 = DateTimeNowCache.GetDateTime();
                Console.WriteLine(now3);
                Console.WriteLine(reYIELD);
         using (StreamWriter file = new StreamWriter(path, true))
                {
                    file.WriteLine(reYIELD);
                    file.Close();
                }
            }

                catch (ApplicationException ex)
                {
                    Console.WriteLine(ex.ToString());
                }
           
                //sa.Soket.Close();
            goto start;
        }
        static void socklan(string saAddress, string saPort)
        {
            try
            {
                sa = new existech(saAddress, int.Parse(saPort));
                //sa.writeLine("*IDN?");
                //sa.writeLine(comsend.Text);
                // this.textreturn.Text = sa.readLine();
            }
            catch (ApplicationException ex)
            //catch (Exception ex)
            {
                //Console.WriteLine(ex.ToString());
               Console.WriteLine(ex.ToString());
            }
        }

        public static class DateTimeNowCache
        {
            /// <summary>
            /// Refresh time after this many requests.
            /// </summary>
            const int _count = 20;

            /// <summary>
            /// The most recent time collected.
            /// </summary>
            static DateTime _recentTime = DateTime.Now;

            /// <summary>
            /// Number of skipped time collections
            /// </summary>
            static int _skipped;

            /// <summary>
            /// Get the DateTime within the last N calls.
            /// </summary>
            /// <returns>Recent DateTime collected.</returns>
            public static DateTime GetDateTime()
            {
                _skipped++;
                if (_skipped > _count)
                {
                    _recentTime = DateTime.Now;
                    _skipped = 0;
                }
                return _recentTime;
            }
        }

如何在不建立新连接的情况下重用连接?

下面是套接字类连接..

class existech
    {

        private string IpAddr;
        private int PortNumber;
        private IPEndPoint ip = null;
        public IPEndPoint Ip
        {
            get
            {
                if (ip == null)
                    ip = new IPEndPoint(IPAddress.Parse(IpAddr), PortNumber);
                return ip;
            }
            set { ip = value; }
        }
        /// <summary>
        /// Spectrum Analyzer Constructor
        /// </summary>
        /// <param name="cihazIPAdres">SA IP address</param>
        /// <param name="cihazPortNo">SA Port Number</param>
        public existech(string instrIPAddress, int instrPortNo)
        {
            IpAddr = instrIPAddress;
            PortNumber = instrPortNo;

            if (!Soket.Connected)
                throw new ApplicationException("Instrument at " + Ip.Address + ":" + Ip.Port + " is not connected");
            else
            {
                // DateTime now = DateTime.Now;
                DateTime now = DateTimeNowCache.GetDateTime();
                Console.WriteLine(now);
                Console.WriteLine("Equipment Connected");
            }
        }

        public void writeLine(string command)
        {
            //  Soket.Send(Encoding.ASCII.GetBytes(command + "\n"));
            Soket.Send(Encoding.ASCII.GetBytes(command + "\r"));
        }

        public string readLine()
        {
            byte[] data = new byte[1024];
            int receivedDataLength = Soket.Receive(data);
            return Encoding.ASCII.GetString(data, 0, receivedDataLength);
        }

        Socket soket = null;

        public Socket Soket
        {
            get
            {
                if (soket == null)
                {
                    soket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    try
                    {
                        if (!soket.Connected)
                            soket.Connect(Ip);
                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine(ex.ToString());
                        //Console.WriteLine("Unable to connect to server.");
                        throw new ApplicationException("Instrument at " + Ip.Address + ":" + Ip.Port + " is not connected");
                    }
                }
                return soket;
            }
            set { soket = value; }
        }

        public static class DateTimeNowCache
        {
            /// <summary>
            /// Refresh time after this many requests.
            /// </summary>
            const int _count = 20;

            /// <summary>
            /// The most recent time collected.
            /// </summary>
            static DateTime _recentTime = DateTime.Now;

            /// <summary>
            /// Number of skipped time collections
            /// </summary>
            static int _skipped;

            /// <summary>
            /// Get the DateTime within the last N calls.
            /// </summary>
            /// <returns>Recent DateTime collected.</returns>
            public static DateTime GetDateTime()
            {
                _skipped++;
                if (_skipped > _count)
                {
                    _recentTime = DateTime.Now;
                    _skipped = 0;
                }
                return _recentTime;
            }
        }
    }

Loginthiren

Loginthiren

推荐答案

您发布了很多代码,但并没有真正弄清自己遇到的问题.根据您发布的代码,existech类将具有一个套接字,该套接字在首次使用时会初始化.此后,您正在对其进行读/写操作.只要你有一个 该类在内存中的实例,您将有一个打开的套接字.

You posted a lot of code but you didn't really clarify what problem you're having. Based upon the code you posted the existech class will have a socket that is initialized on first use. Thereafter you are reading/writing to it. As long as you have a single instance of that class in memory you'll have a single open socket.

但是,对我来说,您的代码有很多问题.首先,您不应该在吸气剂中做任何昂贵的事情.创建套接字应该始终是应用程序要其打开套接字时触发的显式方法调用.那里也应该 是关闭该套接字的相应方法.调试器(甚至是属性枚举)可以触发对getter的调用,除非明确要求这样做,否则您不希望创建套接字.

But, to me, there are lots of issues with your code. Firstly you shouldn't do anything expensive in a getter. Creating a socket should always be an explicit method call triggered by an application at the moment it wants the socket open. There should also be a corresponding way to close that socket. The debugger (or even property enumeration) can trigger a call to the getter and you don't want the socket created unless explicitly told to do so.

另一个问题是套接字是可使用的资源.由于您将其作为类的字段,因此您也需要实现IDisposable.在您的类实例的创建者负责处理完该类(套接字)之后.

Another issue is that a socket is a disposable resource. Since you have it as a field in your class you need to implement IDisposable as well. The responsibility is on the creator of your class instance to dispose of the class (socket) when it is done.

第三,转到.永远没有理由使用goto.用常规循环替换该代码.大多数公司都禁止Gotos.我想不出一个真正的应用程序,goto是正确的选择.

Thirdly, goto. There is no reason to use goto, ever. Replace that code with a regular loop. Gotos are forbidden in most companies. I cannot think of a single, real application where goto is the right choice. 

第四,您的existech类负责套接字的生存期,因此您不应公开socket属性的设置方法.如前所述,可能根本不应该公开套接字,因此请完全删除此属性或将其设为私有.

Fourth, your existech class is responsible for the lifetime of the socket so you shouldn't expose a setter for the socket property. As mentioned earlier the socket probably shouldn't be exposed at all so get rid of this property altogether or make it private.

第五,不要到处都使用static.唯一可能是静态的是您的入口点.您可能可以将入口类的方法设为静态,但我个人建议您将它们创建为普通实例方法,而只需创建一个实例 您在Main的入门课程.除非您真正了解自己在做什么,否则请避免使用静态成员.

Fifth, don't use static everywhere. The only thing that might be static is your entry point. You might possible make methods of your entry class static but I personally recommend that you create them as normal instance methods and simply create an instance of your entry class in Main. Avoid static members unless you really understand what you're doing.

第六,使用套接字是一个非常低级的功能.如果要构建TCP客户端,请改用TcpClient.它处理了使用套接字的底层细节.如果您要构建一个TCP服务器,请改用TcpListener. MSDN中有示例 如何构建TCP客户端和服务器,以及有关如何执行此操作的在线示例.

Sixth, using sockets is a very low level feature. If you are building a TCP client then use TcpClient instead. It handles the low level details of working with sockets. If you're instead building a TCP server then use TcpListener instead. MSDN has examples of how to build TCP clients and servers and there are plenty of examples online on how to do this.


这篇关于如何重用客户端套接字连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆