using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace testIasync
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private string host = "http://192.168.0.99";
private void timer1_Tick(object sender, EventArgs e)
{
DelegateMethod dm = new DelegateMethod(MethodName);
AsyncCallback acb = new AsyncCallback(CallBackMethod);
IAsyncResult iar = dm.BeginInvoke(acb, dm);
}
private delegate void DelegateMethod();
private void CallBackMethod(IAsyncResult ar)
{
DelegateMethod dm = (DelegateMethod)ar.AsyncState;
dm.EndInvoke(ar);
}
/// <summary>
/// 访问网络的方法
/// </summary>
private void MethodName()
{
int second = DateTime.Now.Second;
if (second > 30)
{
host = "http://127.0.0.1";
}
ckNet ck = new ckNet();
bool r = ck.ckServiceStateByUrl(host);
if (r)
{
MState("网络正常");
}
else
{
MState("与服务器无连接");
}
}
private delegate void ModifyState(string str);
private void MState(string str)
{
if (label1.InvokeRequired)
{
ModifyState m = new ModifyState(MState);
label1.Invoke(m, str);
}
else
{
label1.Text = str;
}
}
}
}
上面用到的ckNet的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace testIasync
{
public class ckNet
{
/// <summary>
/// 因为有时服务器配置,会无法响应ping,因此,直接让程序与服务器上某个页面交互,通过返回信息来判断是否能连通服务器
/// </summary>
/// <returns></returns>
public bool ckServiceStateByUrl(string sv)
{
try
{
bool state = false;
if (sv == "") return false;
//交互开始
WebClient w = new WebClient();
System.Collections.Specialized.NameValueCollection VarPost = new System.Collections.Specialized.NameValueCollection();
VarPost.Add("ac", "test");//参数名为ac,值为test,告诉服务器,本次行为是为了测试是否能连接
byte[] byRemoteInfo = w.UploadValues(sv, "POST", VarPost);
string sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);
if (sRemoteInfo == "T")
{
state = true;//获取到服务器上的返回值,则表示与服务器通讯正常
}
return state;
}
catch
{
return false;
}
}
}
}