套接字编程、ASP.Net C#、VS2008
我正在尝试通过计时器控制每 5 秒确定远程(客户端)的状态是连接还是断开连接。每当我第一次启动服务器时,我得到的套接字状态是 connected=true。但是下次我得到套接字状态时为空。
注意:我通过创建类的对象来访问从类到 Aspx 页面的 Socket 状态。
这是我的代码:
页面:
protected void Timer1_Tick1(object sender, EventArgs e)
{
Communication obj=new communication();
bool Rexits=obj.listen();
if(Rexits)
Response.write("Remote is On");
else
Response.write("Remote is Off");
}
**************************************************************************
Communication class:
Socket listener=new Socket();
Socket connection;
public bool listen()
{
listener.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, true);
bool RemoteExits = false;
try
{
if (connection== null)
{
listener.Bind(endPoint);
listener.Listen(pendingConnectionQueueSize);
listener.BeginAccept(AcceptConnection, null);
RemoteExits = IsConnected(connection);
}
return RemoteExits;
}
catch (Exception ex)
{
a = IsConnected(connection);
return RemoteExits;
}
}
//callback method
protected void AcceptConnection(IAsyncResult res)
{
// Make sure listener doesn't go null on us.
lock (this)
{
connection = listener.EndAccept(res);
listener.BeginAccept(AcceptConnection, null);
}
// Close the connection if there are no handlers to accept it!
if (Connected == null)
{
connection.Close();
}
else
{
TcpServer tc=new TcpServer();
Clifton.TcpLib.ConnectionState cs=new
Clifton.TcpLib.ConnectionState(connection,cs);
OnConnected(new TcpServerEventArgs(cs));
}
}
//Poll Mehod
public static bool IsConnected(Socket client)
{
try
{
bool connected = !(client.Poll(1, SelectMode.SelectRead) &&
client.Available == 0);
return connected;
}
catch
{
return false;
}
}