[Python] Asynchronous socket blocking occurs in Unix environments.

Asked 1 years ago, Updated 1 years ago, 302 views

Blocking occurs in an asynchronous socket in a UNIX environment.
(It works as intended on Windows but occurs on Mac, Linux)

Problem creating socket-related library
Forced shutdown of a client connected to the server causes the server to stop.

As a result of debugging, there was a problem with the code that received the data.

# protocol/xtcp/handle.py, line 672.
...
await self._event_loop.sock_recv(socket, packet_size)
...

When the socket breaks The event loop stops because it is blocked by the following code.
파이썬 Documentation Even though the socket was in the non-blocking state accordingly.

Tested in multiple environments
Windows 11, Python 3.10.6 환경

macOS 12.5 (ARM), Python 3.9.13 환경

Ubuntu 20.04, Python 3.8.10 환경

I can't think of a sharp solution other than separating threads using threading.
No matter how much I googled, I couldn't even find a similar case.
What should I do not to eat blocking?

python socket asyncio

2022-12-19 22:42

1 Answers

I couldn't code because I was busy after starting school after the question, but now I'm solving it. I look around C# Docs when I find a problem, and I also found a clue to this problem here: aharef="https://learn.microsoft.com/dn-us/dotnet/api/system.net.sockets.lingeroption.enabled?view=net-6.0" target="_blank">

You can use the Enabled property to determine whether the Socket will linger after closing. Change this value to true or false and pass the altered LingerOption to the SetSocketOption method or set the LingerState or LingerState property.to disable or enable lingering.

The following table describes the behavior for the possible values of the Enabled property and the LingerTime property stored in the LingerState property.

If Linger is disabled, you can see that the socket is active for the time limit specified in the system settings. And so sock.getsockopt(socket.SOL_SOCKET, socket.SO_LINGER)
The following code confirms that Linger is disabled.

If so, if you enable Linger and set the timeout to 0, the socket will immediately disconnect. Therefore, as a result of activating Linger, blocking no longer occurred.

import struct

sock.setsockopt(socket.SOL_SOCKET, 
                socket.SO_LINGER, 
                struct.pack("ii", 1, 0))

If you enter the following code, it will no longer be blocked.


2022-12-20 06:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.