您好,我正在编写将Windows客户端连接到Linux服务器套接字的代码。
我已经可以建立连接了,但是似乎Linux服务器总是在几秒钟后切断我的连接,而没有发回我所需的响应。
我也已经尝试过使用telnet,但是在几秒钟之后,Linux服务器又切断了我的连接。

使用Windows套接字连接到Linux服务器套接字是否有问题?

            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("IPADDRESS"), 6004);
            // Create a TCP/IP  socket.
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Connect the socket to the remote endpoint. Catch any errors.
            try
            {
                if (!sender.Connected)
                    sender.Connect(remoteEP);

                string data = new Client().Test();

                DE_ISO8583 de = new ISO8583().Parse(data);

                data = data.Length.ToString().PadLeft(4, '0') + data;
                byte[] msg = Encoding.ASCII.GetBytes(data);

                int bytesSent = sender.Send(msg);

                //// Receive the response from the remote device.
                int bytesRec = sender.Receive(bytes);
                Console.WriteLine("Received = {0}",
                    Encoding.ASCII.GetString(bytes, 0, bytesRec));

                //sender.Disconnect(true);

                //sender.Shutdown(SocketShutdown.Both);
                //sender.Close();
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }

最佳答案

由于没有活动,服务器可能正在关闭连接。启用keepalive选项将定期向服务器发送一个空的数据报,以保持连接有效。见下面的代码



            TcpClient client = new TcpClient();
            client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);​

10-07 19:48
查看更多