C# 的tcp Socket设置自定义超时时间

 

简单的c# TCP通讯(TcpListener)

C# 的TCP Socket (同步方式)

C# 的TCP Socket (异步方式)

C# 的tcp Socket设置自定义超时时间

C# TCP socket发送大数据包时,接收端和发送端数据不一致 服务端接收Receive不完全

 

 

tcp Socket的超时时间默认20多秒,而实际连上不需1秒时间,20多秒是无法接受的。

 

IPEndPoint ipep = new IPEndPoint(ip, port);//IP和端口
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                ConnectSocketDelegate connect = ConnectSocket;
                IAsyncResult asyncResult = connect.BeginInvoke(ipep, sock, null, null);

                bool connectSuccess = asyncResult.AsyncWaitHandle.WaitOne(TimeOut, false);
                if (!connectSuccess)
                {
                    MessageBox.Show(string.Format("失败!错误信息:{0}", "连接超时"));
                    return false;
                }

                string exmessage = connect.EndInvoke(asyncResult);
                if (!string.IsNullOrEmpty(exmessage))
                {
                    MessageBox.Show(string.Format("失败!错误信息:{0}", exmessage));
                    return false;
                }

                sock.Send(data);//发送信息

                reslen = sock.Receive(response, SocketFlags.None);//接收应答数据包

 

private delegate string ConnectSocketDelegate(IPEndPoint ipep, Socket sock);
        private string ConnectSocket(IPEndPoint ipep, Socket sock)
        {
            string exmessage = "";
            try
            {
                sock.Connect(ipep);
            }
            catch (System.Exception ex)
            {
                exmessage = ex.Message;
            }
            finally
            {
            }

            return exmessage;
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值