TCP断开重连

     在TCP协议中,对于断开的一方其本地用来通讯的端口(系统分配的)仍然会被保留一段时间。所以客户端断开后立即再连就是失败。解决的途径就是换一个本地的通讯端口,由于不能手动指定一个新端口那就只能重新创建TcpClient实例。

在重新创建TcpClient之前要释放掉原TcpClient所占有的资源。

   C#代码:

    

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace OnLineVideo.Util
{
    public class SocketClient
    {

        private TcpClient client;
        private bool isConnection=false;
        private string hostip;//TCP服务器
        private int port;//端口
        //检查网络状态线程
        Thread checkStateThread;
        
        public SocketClient(string hostip, int port)
        {
            this.hostip = hostip;
            this.port = port;

            client = new TcpClient();
            try
            {
                client.Connect(hostip, port);
            }
            catch
            {
                IsConnection = false;
            }
            checkStateThread = new Thread(new ThreadStart(checkState));
            checkStateThread.IsBackground = true;
            checkStateThread.Start();
        }
        /// <summary>
        /// 获取或者设置网络连接状态
        /// </summary>
        public bool IsConnection
        {
            get { return isConnection;}
            set { isConnection = value; }
        }
        private void checkState()
        {
            while (true)
            {
                Thread.Sleep(1000);
                if (client.Connected== false)
                {
                    try
                    {
                        client.Close();
                        client = new TcpClient();
                        client.Connect(hostip, port);
                        IsConnection = true;
                    }
                    catch
                    {
                        IsConnection = false;
                    }
                }

            }
        }
        public void SendCommand(string strMessage)
        {
            try
            {
                byte[] bytesArray = Encoding.ASCII.GetBytes(strMessage+"\n");
                NetworkStream networkStream = client.GetStream();
                networkStream.Write(bytesArray,0,bytesArray.Length);
            }catch
            {
                IsConnection = false;
            }
        }
        public void Close()
        {
            client.Close();
        }  
    }
}

 

 

转载于:https://www.cnblogs.com/WilliamJiang/archive/2012/04/20/2459599.html

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值