How can I check socket state?

This is the code to create and connection socket:

Socket = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateSocket(NAME_Stream, TEXT("ServicesSocket"), false);
TSharedRef<FInternetAddr> Addr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr(Ip, Port);
if(!Socket->Connect(*Addr))
{
...
}

Inside the Tick function I check the data on the sending and receiving:

if (Socket == NULL || Socket->GetConnectionState() != ESocketConnectionState::SCS_Connected))
{
	// do something
}

SendBuf();
Recv();

But even if the connection is in fact already closed by the server, the Socket->GetConnectionState()! = ESocketConnectionState::SCS_Connected always true.

How can I check socket state? Thank you.

Hello,

In standard BSD sockets, if the recv() call returns 0, this indicates the connection was closed gracefully. Currently our wrapper function, FSocketBSD::Recv(), only returns a bool, and doesn’t provide this information, either directly or through GetConnectionState(). We’re now tracking a task to expose this information.

In the meantime, you can work around this in a couple ways:

  1. Modify the Recv() function to
    return an int instead of a bool, return the result of the BSD recv() directly, and check that, or
  2. If you know for sure your socket is an FSocketBSD, you can use GetNativeSocket(), call recv() directly, and check the return value. Note that this will not set the internal LastActivityTime used in GetConnectionState().

Any progress on this?

I would also like to know if GetConnectionState has been updated as yet?

Maybe it will be useful

Maybe looks strange, but works (at least in windows)

{

FSocket* m_Socket;

TArray ReceivedData;

uint32 Size;

while (m_Socket->HasPendingData(Size))

{

int32 Read = 0;

m_Socket->Recv(ReceivedData.GetData(), ReceivedData.Num(), Read);

}

bool HasPendingConnection = false;

bool Res = m_Socket->HasPendingConnection(HasPendingConnection);

}

in case has connection : Res == true & HasPendingConnection == FALSE

in case hasn’t connection : Res == true & HasPendingConnection == TRUE

important: call HasPendingConnection() after Recv()

+1
What’s the status of this method? Is it reliable or not?

+1 Any status update?

It seems that this issue makes it quite difficult if not impossible to use the socket subsystem in a production-ready way (robust and portable) without switching to a source build. At the same time, it seems that fixing it would be really trivial for an Epic staff member?

This issue has been open for over a year now. Any chance in bumping its priority a bit?

I’m also encountering this and would like to see it fixed.

Also, I should mention that I don’t see a way to make Recv non-blocking, so in order to use its return value, I’d need to be okay with blocking. I think there should be a non-blocking method of checking whether the connection is closed.

thank you !! it works!!

+1, Any progress on this?