采用异步,在委托中定义接收方法,有收到,会自动进入委托处理。
加Timer计时3minute,后断开。
TcpClient或socket中有Asy为词头的一系列方法,如AsySend、AsyConnect、AsyRead等等吧,具体函数名记不清了,看看帮助吧,很好解决。
我自已网络开发基础比较差。翻了点资料就上阵了,还有些地方没看明白。以下是我从msdn找的帮助文档中的关键代码,还是不太明白,大家帮忙看看,是不是用这个。注释是我加的。
============================================================//接收方法,静态成员
private static void Receive(Socket client) {
try {
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state); //new AsyncCallback(ReceiveCallback)调用委托,方法ReceiveCallBack;
} catch (Exception e) {
//..
}
}
//以下是ReceiveCallback方法,“IAsyncResult ar”是什么意思?
private static void ReceiveCallback( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
最重要的问题是,这个委托总是能够接收到不定时发过来的数据吗?
只要一有数据发过来,ReceiveCallback方法就能触发吗?
TO: cchinasp(风和影的恋人)
基本上是这样了,不过要注意的是当异步委托ReceiveCallback被触发后,需要再次调用BeginReceive(),还有可以指定接受字节数,利用它可以精确控制完整接受一个有长度描述的自定义报文。
但我觉得好象没有给事件加委托,为什么能够做到呢?
else {
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
// Signal that all bytes have been received.
//在这里加上要调用的委托!!!!!!
receiveDone.Set();
}
都在胡说些啥。除非是长连接,短连接一但被服务器断开,必须重新连接。
通常的做法是每过一段时间发一个空包,来保持这个连接。
对。是要重新连接。但现在我关键是不明白在连上后,如何接收的问题。
终于搞定。正是采用上面的方法。
谢谢各位帮助。