C#异步套接字与C++winsock2之间的通信

communication between C# async sockets and C++ winsock2

本文关键字:之间 通信 C++winsock2 异步 套接字      更新时间:2023-10-16

我正在尝试使用sendfile C#异步套接字的功能(作为服务器),并在C++本地代码客户端接收该文件。当我使用它从C#服务器更新客户端的文件时,由于需要,无法使用webServices。这是我用来发送文件

IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress  ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
// Create a TCP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint.
client.Connect(ipEndPoint);
// There is a text file test.txt located in the root directory.
string fileName = "C:\test.txt";
// Send file fileName to remote device
Console.WriteLine("Sending {0} to the host.", fileName);
client.SendFile(fileName);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();

而且。。。你的问题到底是什么?

我对c#不太熟悉,但在c++上,您可以实例化一个线程,该线程使用select永久侦听传入数据(使其也成为"异步"),然后用同步方法处理它(如有必要,请使用CriticalSection)。

为了澄清这一点,这是服务器/客户端通信的一般工作方法。

服务器:实例化套接字,将自身绑定到端口并侦听传入连接。当连接进入时,执行握手并将新客户端添加到客户端集合中。响应传入请求/向所有客户端发送定期更新

客户:实例化套接字,使用"connect"连接到服务器,并根据协议开始通信。

编辑:只是为了确保,这不是一个微不足道的沟通错误问题,你的意思是如何在客户端保存文件吗?

您可能想要使用以下代码:(假设您在线程中使用select)

fd_set fds;             //Watchlist for Sockets
int RecvBytes;
char buf[1024];
FILE *fp = fopen("FileGoesHere", "wb");
while(true) {
    FD_ZERO(&fds);      //Reinitializes the Watchlist
    FD_SET(sock, &fds); //Adds the connected socket to the watchlist
    select(sock + 1, &fds, NULL, NULL, NULL);    //Blocks, until traffic is detected
    //Only one socket is in the list, so checking with 'FD_ISSET' is unnecessary
    RecvBytes = recv(sock, buf, 1024, 0);  //Receives up to 1024 Bytes into 'buf'
    if(RecvBytes == 0) break;   //Connection severed, ending the loop.
    fwrite(buf, RecvBytes, fp); //Writes the received bytes into a file
}
fclose(fp);                     //Closes the file, transmission complete.