我设置了一个timer控件,每隔几秒钟 就向服务端尝试连接是否成功当连接成功的时候,我就让timer的enable为false,然后调用线程进行数据的接收timer控件的代码如下:
//client是我定义的一个TcpClient
if (client==null) //当client为null的时候,就不断的尝试连接服务端
{
try
{
client = new TcpClient(Dns.GetHostName(), 51888);
}
catch
{
}
}
else
{
this.timer1.Enabled = false;
connecto();
}//connecto()如下代码:
private void connecto()
{
//获取网络流
NetworkStream netStream = client.GetStream();
sr = new StreamReader(netStream, System.Text.Encoding.UTF8);
sw = new StreamWriter(netStream, System.Text.Encoding.UTF8);
Thread myThread = new Thread(new ThreadStart(ReceiveData));
myThread.Start();
}//ReceiveData 代码如下: private void ReceiveData()
{
while (true)
{
string receiveString = null;
try
{
receiveString = sr.ReadLine();
}
catch
{
MessageBox.Show("接收数据失败");
}
if (receiveString == null)
{
MessageBox.Show("与服务器断开连接");
client.close();
client=null;
this.timer1.Enabled = true; //当与服务器断开连接的时候,我就要开启timer1控件,再次不断的进行尝试连接
break;
}
MessageBox.Show("收到:" + receiveString); }我觉得我的思路好像没有问题,就是当我的线程ReceiveData()检测到和服务端断开连接后,就让timer1.Enable=true;
让它再次不断的尝试连接服务端,但是我感到奇怪的是,timer.Enable=true;好像一点用都没有,那个timer控件也不会再次执行了,究竟是什么原因呢??哪位大哥说下,谢了!!
//client是我定义的一个TcpClient
if (client==null) //当client为null的时候,就不断的尝试连接服务端
{
try
{
client = new TcpClient(Dns.GetHostName(), 51888);
}
catch
{
}
}
else
{
this.timer1.Enabled = false;
connecto();
}//connecto()如下代码:
private void connecto()
{
//获取网络流
NetworkStream netStream = client.GetStream();
sr = new StreamReader(netStream, System.Text.Encoding.UTF8);
sw = new StreamWriter(netStream, System.Text.Encoding.UTF8);
Thread myThread = new Thread(new ThreadStart(ReceiveData));
myThread.Start();
}//ReceiveData 代码如下: private void ReceiveData()
{
while (true)
{
string receiveString = null;
try
{
receiveString = sr.ReadLine();
}
catch
{
MessageBox.Show("接收数据失败");
}
if (receiveString == null)
{
MessageBox.Show("与服务器断开连接");
client.close();
client=null;
this.timer1.Enabled = true; //当与服务器断开连接的时候,我就要开启timer1控件,再次不断的进行尝试连接
break;
}
MessageBox.Show("收到:" + receiveString); }我觉得我的思路好像没有问题,就是当我的线程ReceiveData()检测到和服务端断开连接后,就让timer1.Enable=true;
让它再次不断的尝试连接服务端,但是我感到奇怪的是,timer.Enable=true;好像一点用都没有,那个timer控件也不会再次执行了,究竟是什么原因呢??哪位大哥说下,谢了!!
解决方案 »
- 如何实现XtraTreeList与GridControl控件的交互
- 还是JS问题:JS对ASP.NET的Radiobutton调用
- 请问在网页中如何播放所有格式的视频文件?
- 关于TreeView生成时的IndexOf值获取、传输的问题
- C# 调用MFC DLL 遇到的问题,错误:内存分配访问失效------>>>>
- Timer控件控制Progressbar进度不好使,求助大虾
- 关于用ole_db连接oracle出现中文为???的问题?
- 取得当前DLL路径用哪个API
- 附件大小的判断~~~急
- 怎样实现对指定服务器进行数据访问?
- 为什么sqldatareader没有数据
- C#访问sqlserver mobile 2005的问题
还有一种处理办法:不用timer控件,直接在需要启动timer的时候创建timer类对象
不知是否有帮助
http://www.builder.com.cn/2007/1104/604529.shtmlhttp://www.cnblogs.com/xugang/archive/2008/04/15/1154689.htmlhttp://www.cnblogs.com/hexiaosheng/archive/2008/04/14/1152311.html