本文介绍了如何确定套接字是否已关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个简单的客户端服务器程序,但主要问题是一旦在客户端和服务器之间建立了连接,如果客户端关闭程序,服务器就会重复执行最后一条消息,这有时会产生巨大的问题.所以我想要的是,如果有任何我可以调用的函数来获取 SOCKET 结构的状态,那么如果客户端关闭程序,服务器就会知道停止.我只需要从函数中查找坏套接字的函数.顺便说一下,我正在用 Win32 c 编写这个程序.我试过 if(mySocket==SOCKET_ERROR) 这似乎不起作用......除非我用错了.我刚刚开始建立网络.

I have a simple client server program that I made but the main issue is that once a connection is established between the client and server, if the client closes the program, the server repeatedly executes the last message and that creates huge problems sometimes. So what I want to is if there is any function that I can call to get the state of a SOCKET structure so if the client closes the program, the server will know to stop. I just need the function what to look for from the function for a bad socket. By the way I am writing this program in Win32 c. I tried if(mySocket==SOCKET_ERROR) which didn't seem to work... unless I used it wrong. I'm just beginning networking.

if(!sockServer.RecvData( recMessage, STRLEN )){return 0;}
// where
bool Socket::RecvData( char *buffer, int size )
{
    int i = recv( mySocket, buffer, size, 0 );
    if(!i){return false;}
    buffer[i] = '\0';
    return true;
}  //this isn't working

推荐答案

如果对端关闭套接字,read()recv() 将返回零.您必须忽略如果服务器重复执行最后一条消息",这当然会造成巨大问题",不仅仅是有时",而是总是.

If the peer closes the socket, read() and recv() will return zero. You must be ignoring that if 'the server repeatedly executes the last message', which of course would 'create huge problems' not just 'sometimes' but always.

编辑 1:您还犯了另一个基本的 TCP 编程错误:您假设您在一次阅读中收到了完整的消息.TCP 中没有消息,它只是一个字节流,写入和读取之间没有 1::1 对应关系(send()recv()).recv() 可以返回零或少至 1 个字节.你必须组织你自己的消息边界,你必须循环直到收到你可以处理的完整消息.

EDIT 1: You're also making another elementary TCP programming error: you are assuming that you receive an entire message in a single read. There are no messages in TCP, it's just a byte stream, and no 1::1 correspondence between writes and reads (send() and recv()). recv() can return zero or as few as 1 bytes. You have to organize your own message boundaries, and you have to loop until you receive an entire message you can deal with.

编辑 2:您还忽略了接收方法中的所有错误.您必须寻找返回 -1` 的 recv(),而不是继续处理您试图读取的数据的逻辑.您至少应该调用 perror() 或检查 errno 或任何 Winsock 等效项.

EDIT 2: You are also ignoring all errors in your receive method. You must look for recv() returning -1`, and not proceed with the logic that processes the data you were trying to read. At a minimum you should call perror() or check errno or whatever the Winsock equivalent is.

当您收到错误或 EOS 时,您必须停止循环、关闭套接字、忘记连接并忘记此客户端.

When you get either an error or an EOS you must stop looping, close the socket, forget about the connection, and forget about this client.

这篇关于如何确定套接字是否已关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 03:23
查看更多