Socket.IO Server with Python
python-socket.io-server-unity-client

Socket.IO Server with Python

We are back with another language and framework for the game's backend communication.

Please see the previous related articles for a detailed understanding of this guide. If you know about client-server and remote procedure calls then you may not need to waste time on previous articles.

Links are here:

Steps included in this article:

  • Install python
  • Install the required packages
  • Create a new application with a basic server setup

Install python

Please follow the guidelines for the installation of the related operating system. You can download it from here.

Install the required packages

We need these packages for our server:

  1. socket.io
  2. eventlet

We will set up the project now. In Python, we have some terms known as LOCAL ENVIRONMENT(not doing it) and GLOBAL ENVIRONMENT.

  • Local Environment: Python refers to the environment in which your Python code runs on your local computer. By creating a local environment, you can install and manage specific versions of Python packages and dependencies for your project without affecting other projects or your system Python installation. This process feels complex to beginners. WE WILL NOT BE TOUCHING IT NOW.
  • Global Environment: Each environment is composed of the specific Python interpreter, its standard library, a set of pre-installed packages, and any other packages you install while that environment is activated. Installing a package into a global environment makes it available to all projects using that environment.

We will install the packages in the global environment to use the installed Python interpreter in the global environment.

Here's a step-by-step guide to setting up a Python project:

  • Choose a project directory
  • Create the script inside the directory with the extension "yourName.py". I'm using server.py.
  • Run the following command in the terminal. I will be using the vscode terminal.

py -m pip install eventlet python-socketio        

For me, py is working well. You can also try "py" and "python" as well. Like

python -m pip install eventlet python-socketio        

At this point, we have the packages in the global environment.

Create a new application with a basic server setup

Now we will implement the server-side code in the following steps:

  • Import dependencies
  • Create required objects
  • Define functions for socket.io connections

Start writing the code in the server.py. We will import the required libraries for our code to run. We need socketio and eventlet.

import socketio
import eventlet        

Now we will create objects for the server and files to serve by the server.

sio = socketio.Server(async_mode='eventlet')
app = socketio.WSGIApp(sio, static_files={
? ? '/': {'content_type': 'text/html', 'filename': 'index.html'}
})        

These lines of code are used to set up a Socket.IO server using the Python Socket.IO library.

  1. The first line creates a SocketIO server instance using the `async_mode` parameter set to 'eventlet'. This specifies the type of asynchronous processing that the server will use to handle incoming connections and messages. In this case, the 'eventlet' mode is used, which allows for non-blocking I/O and concurrency.
  2. The second line creates a WSGI (Web Server Gateway Interface) application that will handle incoming HTTP requests to the server. The `WSGIApp` function takes the `sio` SocketIO server instance as an argument, along with a dictionary of static files that will be served by the server. In this case, the static file is an `index.html` file that will be served at the root URL ('/').

In simple terms, these lines of code set up a SocketIO server that can handle incoming connections and messages using the 'eventlet' mode of asynchronous processing. The server is configured to serve an HTML file as the root URL.

Now we will define the events for Socket.IO framework. We need the following events to handle:

  • Client connection: "connect" required a predefined event
  • Client disconnect: "disconnect" required a predefined event
  • Client response: "response" event (Not sure about this event)
  • Client message: "message" custom user-defined event

You can READ more about events here.

Let's see the connect event in Python:

@sio.event
def connect(sid, environ):
? ? print('server connected to client with session ID = ?',sid)        

What the hell is "@sio.event" ???????????????

It is the keyword used to declare a python function as a socket.io event.

Disconnect event:

@sio.event
def disconnect(sid):
? ? print('disconnect=>SERVER ', 'SID: ',sid)        

Response event:

@sio.event
def response(sid,recdata):
? ? print(recdata)        

and last but not least our user-defined event the "message" event:

@sio.event
def message(sid,data):
? ? sio.send(data)
? ? print('data sent from server '+ data)        

At this point, your code must look like this:

No alt text provided for this image
base server setup ready

We have our server ready now. What is next ??????????????

We need to execute our server and test it. BUtttttttt how out app object and sio object will be used to execute ??????

We have many ways to do it but I will share only one of them. That is below:

if __name__ == '__main__':
? ? eventlet.wsgi.server(eventlet.listen(('', 3000)), app)        

The code `if __name__ == '__main__':` is a conditional statement that checks whether the current module is being executed as the main program or if it is being imported by another module.

If the module is being executed as the main program, the `if` statement is `True` and the code block within it is executed. If the module is being imported, the `if` statement is `False` and the code block within it is not executed.

In the context of a Socket.io server, this code is important because it starts the server listening on a specific port when the module is executed as the main program. Specifically, the `eventlet.wsgi.server` function starts a new WSGI (Web Server Gateway Interface) server on port 5000 using the `eventlet.listen` function, which listens for incoming connections on all available network interfaces (`''`).

The `app` variable passed as an argument to `eventlet.wsgi.server` is a WSGI-compliant application, in this case, a `socketio.WSGIApp` instance that wraps the `sio` SocketIO server instance.

By placing the server startup code within the `if __name__ == '__main__':` block, we ensure that the server only starts when the module is executed as the main program, which is the expected behavior for a standalone Socket.io server.

Overall, this code is important for starting a Socket.io server that listens on a specific port and responds to incoming connections from clients. The conditional check ensures that the server is only started when the module is executed as the main program, which is the expected behavior for a standalone server.

Now our code will look like this:

import socketio
import eventlet

sio = socketio.Server(async_mode='eventlet')
app = socketio.WSGIApp(sio, static_files={
? ? '/': {'content_type': 'text/html', 'filename': 'index.html'}
})


@sio.event
def connect(sid, environ):
? ? print('server connected to client with session ID = ?',sid)


@sio.event
def message(sid,data):
? ? sio.send(data)
? ? print('data sent from server '+ data)


@sio.event
def response(sid,recdata):
? ? print(recdata)


@sio.event
def disconnect(sid):
? ? print('disconnect=>SERVER ', 'SID: ',sid)


if __name__ == '__main__':
? ? eventlet.wsgi.server(eventlet.listen(('', 3000)), app)        

Now we will run the server and test it with our Unity client. Use the command below:

py server.py
or
python server.py        

How it will start:

No alt text provided for this image
python-start-server

Unity client condition:

No alt text provided for this image
unity-client-for-python

The server on connection:

No alt text provided for this image
python-server-on-connection

Thank you for all to be here. Please let me know about the problems.

#python #socketio #socket #gamedev #multiplayer #unity #unity3d #unitydeveloper #clients #serverside #servers #communication

Moazan Amjad

Senior Unity Developer | Unity Game Development

1 年

Thoroughly understandable. Nice Job.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了