使用c#连接到远程主机并读取数据

本文关键字:主机 读取 数据 连接 程主机 使用 | 更新日期: 2023-09-27 18:06:41

我有一个服务器,一旦你连接到它,它就会在TCP端口上传输数据。您可以看到,如果您telnet到TCP端口,数据开始流动。

我正在寻找一个例子,让我连接到一个IP地址和端口,并在应用程序的流中接收数据。

我能找到的所有例子都是客户端-服务器模型,客户端发送(这不是我需要的),服务器绑定到自己的端口并接收。

我需要这是异步的,我相信这是可以做到的,但我可以做一个好的腿!

使用c#连接到远程主机并读取数据

如果您使用的是TcpClient,则使用GetStream获取NetworkStream,然后使用流读取服务器发送的数据。您始终可以使用BeginRead异步地使用流。

如果你使用的是普通的Socket,你可以使用BeginReceive在连接后异步接收。

无论哪种方式,只要您绑定并连接了NetworkStreamSocket对象,服务器或客户端之间就没有区别。您可以使用读取客户机代码的服务器示例,通常不需要(或很少)修改。

例如:

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);
}