C#异步套接字与C++winsock2之间的通信
communication between C# async sockets and C++ winsock2
我正在尝试使用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.
相关文章:
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 通过插槽和信号在不同线程中的两个qt对象之间进行通信
- C++ 两台不同机器之间通过wifi进行套接字通信
- 线程之间的通信不起作用 - C++
- 通过USB在PC和Arduino之间进行串行通信
- 管理器类和对象类之间的通信
- 使用命名管道在 C# 和C++应用程序之间进行持续通信
- Python 3 套接字和 QTcpsocket (c++) 之间的通信失败
- 如何在嵌入式浏览器和Webside之间进行双向通信
- C++程序和未识别程序之间的双向通信
- 使用C++在同一系统上运行的 2 个服务之间进行通信
- C# 和C++应用程序之间的通信
- 如何在Qt WebChannel中以独立于平台的方式在HTML/Javascript和C++之间进行通信?
- 如何在 gtk+ c 中的回调之间进行通信
- Electron应用程序和Win32本机桌面应用程序之间的进程间通信
- 如何在线程之间进行通信和等效的waitforsingleobject()
- C++ 和 Simulink 之间通过 UDP 进行通信
- 在两个Windows QT5之间进行通信
- 覆盆子Pi(QT C )和Arduino(Arduino IDE)之间的通信
- UNIX中两个进程之间通信的最佳方式:一个运行ruby服务器,另一个运行C++客户端