我有一台服务器,一旦连接到TCP端口,就会将数据流出.如果你telnet到TCP端口并且数据开始流动,你可以看到这个.
我正在寻找一个示例,让我连接到IP地址和端口,并在应用程序的流中接收数据.
我能找到的所有示例都是客户端 - 服务器模型,客户端发送(这不是我需要的),服务器绑定到自身端口并接收.
我需要这个是异步的,相信这可以做到,但我可以做好腿!
如果您正在使用a TcpClient,GetStream用于获取NetworkStream然后使用流来读取服务器发送的数据.您始终可以使用异步方式使用流BeginRead.
如果您使用的是普通旧设备Socket,则可以BeginReceive在连接后用于异步接收.
无论哪种方式,只要您拥有绑定和连接NetworkStream的Socket对象或对象,服务器或客户端之间就没有区别.您可以使用客户端代码中的读取服务器示例,通常没有(或很少)修改.
举个例子:
byte[] readBuffer = new byte[1000];
{
TcpClient tcpClient = new TcpClient(serverHost, serverPort);
NetworkStream stream = tcpClient.GetStream();
stream.BeginRead(readBuffer, 0, 1000, readHandler, tcpClient);
}
...
byte[] tempBuff = new byte[1000];
int tempBuffSize = 0;
// This is a rough example of reading and handling data
// that is delimited by \r\n. This code most probably is
// missing many edge case handling, so use it only as a starting
// point
void readHandler(IAsyncResult result)
{
TcpClient tcpClient = (TcpClient)result.AsyncState;
int dataLen = tcpClient.GetStream().EndRead();
int currStart = 0;
int currEnd = -1;
for (int i = 0; i < dataLen; i++)
{
if (readBuffer[i] == '\r' && i < (readBuffer.Length - 1) &&
readBuffer[i + 1] == '\n')
{
// Set the end of the data
currEnd = i - 1;
// If we have left overs from previous runs:
if (tempBuffSize != 0)
{
// Allocate enough space for the joined buffer
byte[] joinedData = new byte[tempBuffSize + (currEnd - currStart + 1)];
// Get the leftover from the previous read
Array.Copy(tempBuff, 0, joinedData, 0, tempBuffSize);
// And add the current read as well
Array.Copy(readBuffer, currStart, joinedData, tempBuffSize, (currEnd - currStart + 1));
// Now handle it
HandleData(joinedData, 0, joinedData.Length);
// Mark that we don't have any leftovers anymore
tempBuffSize = 0;
}
else
{
// Handle the data, from the start to the end, between delimiter
HandleData(readBuffer, currStart, currEnd);
}
// Set the new start - after our delimiter
currStart = i + 2;
}
}
// See if we still have any leftovers
if (currStart < dataLen)
{
Array.Copy(readBuffer, currStart, tempBuff, 0, dataLen - currStart);
tempBuffSize = dataLen - currStart;
}
// Set the asynchronous read again
stream.BeginRead(readBuffer, 0, 1000, readHandler, tcpClient);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2765 次 |
| 最近记录: |