pygame-web / pygbag

python and pygame wasm for everyone ( packager + test server + simulator )
https://github.com/pygame-web
MIT License
338 stars 39 forks source link

Unable to establish network connection within the web container #137

Closed KyleS98 closed 9 months ago

KyleS98 commented 1 year ago

It appears that networking is not supported. I'm trying to make a multiplayer game using this.

Where would I begin to experiment with adding it?

pmp-p commented 1 year ago

Networking is supported for Websocket and WebRTC network. But no easy sample is available yet, you are welcome to embark for discovering/testing/documenting on pygame community discord

frobnitzem commented 10 months ago

I see the same issue. Here's some sample code,

# main.py
import socket
import pygame

async def sock_open(sock, host, port):
    while True:
        try:
            sock.connect( (host, port) )
        except BlockingIOError:
            await asyncio.sleep(0)
            continue
        except OSError as e:
            # 30 emsdk, 106 linux means connected.
            if e.errno not in (30, 106):
                raise
        return

pygame.init()
screen = pygame.display.set_mode((640, 480))

async def main():
    screen.fill((255, 10, 10))
    sock = socket.socket()
    #sock.connect(("localhost", 50008))
    await sock_open(sock, "localhost", 50008)
    sock.send(b"hello")
    sock.recv(100)
    while running:
        screen.fill((40, 40, 40))
        ...

For the server side, I used the example from: https://pypi.org/project/websockets/

Neither the simple sock.connect nor the error handling version succeed. The game loop does not start. In fact, the screen stays black. It does not show either red or grey like I would expect.

Interestingly, changing the main code to

async def main():
    screen.fill((255, 10, 10))
    sock = socket.socket()
    sock.connect(("localhost", 50008))
    while running:
        screen.fill((40, 40, 40))
        ...

shows the same frozen black screen, but commenting out sock.connect starts. My guess is that sock.connect hangs, and the screen isn't drawn because of buffering.

pmp-p commented 10 months ago

i strongly recommend you start from pygbag base test and not from random websocket desktop code. emscripten underlying emulation of bsd sockets is VERY incomplete and will get you headbanging soon.

So start from what is known to run and elaborate upon by trial and error the reference test : https://github.com/pygame-web/showroom/blob/main/src/test_socket_irc.py ( you can use the irc server in there and connect to it on port 16667 with a real desktop client for debugging (or chatting with me on #sav or #pygbag-0 channels )

a vfork model based upon that irc snippet is here : https://github.com/pygame-web/pygbag.net ( get a app number from me for real use )