Socket.IO Server with Python
Muhammad Afzaal
Unity | C# | Python | Node.js | Backend | Interactive Experience | GenAI
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
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:
We will set up the project now. In Python, we have some terms known as LOCAL ENVIRONMENT(not doing it) and GLOBAL 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:
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:
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.
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:
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:
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:
Unity client condition:
The server on connection:
Thank you for all to be here. Please let me know about the problems.
Senior Unity Developer | Unity Game Development
1 年Thoroughly understandable. Nice Job.