# Using async socket network

**URL:** <https://discourse.slicer.org/t/using-async-socket-network/35654>\
**Category:** Development\
**Created:** [April 22, 2024, 9:58am UTC](https://discourse.slicer.org/t/using-async-socket-network/35654 "2024-04-22T09:58:52Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![dael0207](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/dael0207/32/70087_2.png) [@dael0207](https://discourse.slicer.org/u/dael0207)\
**Post date:** [April 22, 2024, 9:58am UTC](https://discourse.slicer.org/t/using-async-socket-network/35654/1 "2024-04-22T09:58:52Z")

</div>

Hello Slicer community.  
I’d like to incorporate a function within Slicer that asynchronously waits for reception.  
What I want is for the function to execute when Slicer is turned on, asynchronously wait for reception, and if received, send the corresponding value.  
I’d like this function to continue running asynchronously independently of other functions.  
My function looks like

```auto
async def ServerOpen(self):
        HOST = '127.0.0.1'
        PORT = 65432
        print("server open")
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((HOST, PORT))
            s.listen()

            print(f"{HOST}:{PORT}")

            while True:
                conn, addr = await loop.sock_accept(s)
                await self.receive_data(conn) 

    async def receive_data(self, conn):
        def convert_to_doubles(input_string):
            length = len(input_string)
            result = []

            for i in range(0, length, 2):
                substring = input_string[i:i+2]  
                num = float(substring)  
                result.append(num)  

            return result

        while True:
            data = await loop.sock_recv(conn, 1024)
            if not data:
                break

            received_message = data.decode()
            
            await loop.sock_sendall(conn, data)

            numbers = convert_to_doubles(received_message)
            print( numbers[0], numbers[1], numbers[2])
         

            center = [numbers[0], numbers[1], numbers[2]] 
            radius = 6.0 

          
            sphereSource = vtk.vtkSphereSource()
            sphereSource.SetCenter(center[0], center[1], center[2])
            sphereSource.SetRadius(radius)
            sphereSource.SetPhiResolution(30)
            sphereSource.SetThetaResolution(30)
            sphereSource.Update()

           
            sphere = sphereSource.GetOutput()

           
            renderer = slicer.app.layoutManager().threeDWidget(0).threeDView().renderWindow().GetRenderers().GetFirstRenderer()
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputData(sphere)
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            renderer.AddActor(actor)
            renderer.ResetCamera()

            
            slicer.app.layoutManager().threeDWidget(0).threeDView().renderWindow().Render()

```

Where and how should I insert this Python code? Thank you very much as always.

---

<div class="post-metadata">

**Author:** ![pieper](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/pieper/32/8_2.png) [@pieper](https://discourse.slicer.org/u/pieper)\
**Post date:** [April 22, 2024, 2:12pm UTC](https://discourse.slicer.org/t/using-async-socket-network/35654/2 "2024-04-22T14:12:42Z")

</div>

Slicer uses Qt’s event loop, not python’s asyncio. You can look at the code for OpenIGTLink, which I believe uses a timer to periodically check for events, or the WebServer, which uses [QSocketNotifier](https://github.com/Slicer/Slicer/blob/main/Modules/Scripted/WebServer/WebServer.py#L347) so that events are generated when the network is active.

---

<div class="post-metadata">

**Author:** ![dael0207](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/dael0207/32/70087_2.png) [@dael0207](https://discourse.slicer.org/u/dael0207)\
**Post date:** [April 24, 2024, 3:21am UTC](https://discourse.slicer.org/t/using-async-socket-network/35654/3 "2024-04-24T03:21:45Z")

</div>

Dear pieper, Thanks to you, it helped me solve the problem  
But there’s another problem with the lack of modules

```auto
os.system("pip install PyQt5")
from PyQt5.QtNetwork import QTcpServer

```

I tried to solve it with this code, but when I run the executable, the module doesn’t install

```auto
from PyQt5.QtNetwork import QTcpServer
ModuleNotFoundError: No module named 'PyQt5'

```

error is like this, How do I add the code to install the module?  
thanks to you every time! 🙂

---

<div class="post-metadata">

**Author:** ![pieper](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/pieper/32/8_2.png) [@pieper](https://discourse.slicer.org/u/pieper)\
**Post date:** [April 24, 2024, 12:37pm UTC](https://discourse.slicer.org/t/using-async-socket-network/35654/4 "2024-04-24T12:37:59Z")

</div>

Slicer’s architecture is different, so you can’t use PyQt, but instead use PythonQt, which is pre-loaded in the Slicer python environment in the `qt` package. So you would use a line like `qt.QTcpServer()`. It’ll help you to go through the [developer tutorials](https://www.slicer.org/wiki/Documentation/Nightly/Training#Tutorials_for_software_developers) to learn some of the specifics of the Slicer environment.

---

<div class="post-metadata">

**Author:** ![dael0207](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/dael0207/32/70087_2.png) [@dael0207](https://discourse.slicer.org/u/dael0207)\
**Post date:** [May 12, 2024, 2:25pm UTC](https://discourse.slicer.org/t/using-async-socket-network/35654/5 "2024-05-12T14:25:33Z")

</div>

Thank you so much sir. I made a code based on your advice.  
There’s a little bit of a problem with the code. The function seems to work, but when I run the executives, it only runs cmd and the Slicer UI doesn’t. I want to make the function of this wait for reception similar to Asynco and send a specific code if it gets it after doing something else. I always appreciate it so much and I’d really appreciate any advice.

My code is as follows `self.server = MyTcpServer()  
self.server.listen(qt.QHostAddress(“127.0.0.1”), 65432)

```
    # Timer setting
    self.timer = qt.QTimer()
    self.timer.timeout.connect(self.checkClientData)
    self.timer.start(1000)
    print("connect")

```

```auto
Init MyTcpServer is in NavigationWidget's sepup Method and

```

```
def checkClientData(self):
    for socket in self.server.children():
        if isinstance(socket, qt.QTcpSocket):
            if socket.bytesAvailable():
                data = socket.readAll()
                print("Received data from client:", bytes(data).decode())
            else:
                pass`

```

and my Class is

```auto
class MyTcpServer(qt.QTcpServer):
    def __init__ (self, parent=None):
        super(). __init__ (parent)
        self.newConnection.connect(self.handleConnection)

    def handleConnection(self):
        client_socket = self.nextPendingConnection()
        client_socket.readyRead.connect(self.readData)

    def readData(self):
        client_socket = self.sender()
        if client_socket is not None:
            data = client_socket.readAll()
            print("Received data from client:", bytes(data).decode())   

```

always thanks very much

---

<div class="post-metadata">

**Author:** ![pieper](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/pieper/32/8_2.png) [@pieper](https://discourse.slicer.org/u/pieper)\
**Post date:** [May 12, 2024, 3:50pm UTC](https://discourse.slicer.org/t/using-async-socket-network/35654/6 "2024-05-12T15:50:01Z")

</div>

> [@dael0207](#):
>
> The function seems to work, but when I run the executives, it only runs cmd and the Slicer UI doesn’t

I don’t understand exactly what you mean here. Can you describe more?

It should happen that QSocketNotifier, as I mentioned earlier, make the entire process event-driven and efficient and generally doesn’t require timers or UI blockage. Try the [WebServer](https://slicer.readthedocs.io/en/latest/user_guide/modules/webserver.html) and look at the [implementation](https://github.com/Slicer/Slicer/blob/main/Modules/Scripted/WebServer/WebServer.py#L510).

---

<div class="post-metadata">

**Author:** ![pieper](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/pieper/32/8_2.png) [@pieper](https://discourse.slicer.org/u/pieper)\
**Post date:** [May 12, 2024, 3:51pm UTC](https://discourse.slicer.org/t/using-async-socket-network/35654/7 "2024-05-12T15:51:17Z")

</div>

Also if you still need help debugging, make a [self-contained](http://www.sscce.org/) example so that others can see exactly what you are trying to do.
