Reuse a TcpClient in c#

白昼怎懂夜的黑 提交于 2021-01-29 11:10:37

问题


We have a device that accepts ascii messages over a wireless network, and then responds with a value and I have successfully implemented this in a Windows Forms 2010 solution in c#.

I wrote this as a test solution to prove the technology and the actual calls to the device will be made on a Motorola MC55 handheld device.

I have now written an additional test solution in Visual Studio 2008 and installed this onto a device, but the connection to the TcpClient takes around 30 seconds every time its called on the mobile device, where as on the windows solution it's almost instant.

This is far too slow, so I have started looking at reusing the TcpClient, but not had any success and wondered if anyone else has had similar issues and to ask how they got around it, or if anyone can offer any advice on how to reuse a TcpClient so I don't have to create a new one every time I want to make my call.

The code for the connection is shown below...

     public static string GetValueFromDevice(string deviceIPAddress, int devicePort, string messageSentToDevice)
    {
        string returnValue = "";

        try
        {
            TcpClient client = new TcpClient(deviceIPAddress, devicePort);

            byte[] inData = System.Text.Encoding.ASCII.GetBytes(messageSentToDevice);
            NetworkStream stream = client.GetStream();
            stream.Write(inData, 0, inData.Length);

            byte[] outData = new Byte[256];
            int bytes = stream.Read(outData, 0, outData.Length);
            returnValue = System.Text.Encoding.ASCII.GetString(outData, 0, bytes);

            stream.Close();
            client.Close();
        }
        catch (Exception ex)
        {
            returnValue = ex.Message;
        }

        return returnValue;
    }

回答1:


You can leave the TcpClient open as long as you like. Keep the client and stream variables as part of the class (instead of in the function), and don't call Close() until you're done.




回答2:


You can persist and re-use the client and stream and place the code into a separate thread.

But, I do not believe the client needs about 30 seconds to initialize. I see that slow init for TCP client when having an ActiveSync connection, but if you have a wireless only connection, it should init immediately.

So also check your network setup. After first VS deploy and debug session using Active Sync, Visual Studio is able to re-use the determined wireless IP address and runs subsequent deploy/debug sessions via the wireless TCP/IP (if ActiveSync on PC is set to allow Data connections during AS connections).



来源:https://stackoverflow.com/questions/21314413/reuse-a-tcpclient-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!