Python udp socket not closing

Hi, when I run the code below in a Grasshopper Python script, it fails because socket s is not closed. In CPython this code works fine. Does anyone has an idea? Thanks a lot! Best, Kris

import socket
addr = ("127.0.0.1", 65432)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(addr)
s.shutdown(socket.SHUT_RDWR)
s.close()
s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s2.bind(addr)
s2.shutdown(socket.SHUT_RDWR)
s2.close()

Hi @sirkrisp,

Have you already tried using with instead? The socket connection should be closed once the with statement has concluded, without the need to call socket.close().

import socket

HOST = "127.0.0.1"
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()

Why are you trying to bind the same host and port twice?

I only spawn a second socket here to demonstrate that the first one does not close. I just checked the with statement - but it seems that in IronPython it is not implemented:

Runtime error (MissingMemberException): '_socketobject' object has no attribute '__exit__'

Traceback:
  line 10, in script
1 Like