在Windows中的套接字上使用fprintf

我正在尝试在Windows上的套接字上使用fprintf。 许多在线示例都是UNIX示例 。 Windows的等效代码就是我在这里要问的。

最后,我想这样做:

fprintf(file_handle_to_socket, "hello world\r\n"); 

我不想使用WriteFile,snprintf或其他任何东西。 只是fprintf()。

或多或少显示步骤的伪代码将是有帮助的。

这是我到目前为止:

 unsigned short port = enter_port; int result = 0; WSADATA wsaData; result = WSAStartup(MAKEWORD(2, 2), &wsaData); struct sockaddr_in local; memset(&local, 0, sizeof(struct sockaddr_in)); local.sin_port = htons(port); local.sin_family = AF_INET; local.sin_addr.s_addr = htonl(INADDR_ANY); int sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == INVALID_SOCKET) { fprintf(stdout,"invalid socket: error code %d\n", WSAGetLastError()); } result = bind(sock, (struct sockaddr*)&local, sizeof(struct sockaddr_in)); if(result == SOCKET_ERROR) { fprintf(stdout,"bind() failed: error code %d\n", WSAGetLastError()); } result = listen(sock, 5); struct sockaddr peer; memset(&peer, 0, sizeof(struct sockaddr)); SOCKET client = 0; int size = sizeof(struct sockaddr); client = accept(sock, &peer, &size); int OSFileHandle = _open_osfhandle(client, _O_APPEND); FILE * file_handle_to_socket = fdopen(OSFileHandle, "w+"); fprintf(file_handle_to_socket, "Hello World\r\n"); // hoping this helps -- it doesn't fflush(file_handle_to_socket); fclose(file_handle_to_socket); closesocket(client); // this throws an exception WSACleanup(); 

当我运行它时,另一端没有任何东西(使用putty),我在WSACleanup()中得到一个exception; WSACleanup的exceptionAn invalid handle was specified

更新我通过更仔细地阅读这篇文章找到了强有力的领导。 如果我更换:

 fprintf(file_handle_to_socket, "Hello World\r\n"); 

 fprintfsock(client, "Hello World\r\n"); 

有用。

尽管如此,它仍然不是我的问题的完整答案。 我想直接使用fprintf()。

套接字不是文件句柄,因此您不能使用_open_osfhandle()来包装它。 这就是fprintf()无法正常工作的原因。 fprintfsock()专门设计用于直接使用套接字。 它只是一个包装器,将数据格式化为本地缓冲区,然后使用套接字API send()函数发送它。 如果你真的想要将fprintf()与套接字一起使用,则必须使用#undef fprintf然后#define fprintf()将其重新映射到fprintfsock() (只有在使用支持可变参数的编译器时才能使用它)宏)。 否则,只需直接使用fprintfsock()

我有一个类似的问题与使用mingw的套接字上的客户端部分fprintf ,你应该尝试在非重叠模式下创建套接字:

 int sock = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, 0);