Skip to content

[Python] How to Use Socket in Python

Last Updated on 2021-06-02 by Clay

I originally planned to write a simple tutorial of ChatBot using Socket, that would only repeat what you said. Which is similar to the current LineBot tutorial on the internet. The difference is that I using Socket but LineBot I have seen that most are implemented using "webhook".

After thinking, because I want to build a simple UI for my "Socket ChatBot", so I will split my tutorial note to two articles, the first one record how to use socket, the next one record the application of socket.

If you want to research the package "socket" in Python, maybe you can refer to their official website: https://docs.python.org/3/howto/sockets.html

Ok, let's start!


Socket

Socket is developed by Berkeley University, we can think of it as a communication tool on the internet. Using this tool we can build a Server port and a Client port in different computers, and then we can connect them and send messages by each other.

In Python language, there is a package named "socket", and we don't use any command to install it, just import.

The following is a simple example.


Server.py

# -*- coding: utf-8 -*-
import socket
HOST = '127.0.0.1'
PORT = 8000

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(10)

while True:
    conn, addr = server.accept()
    clientMessage = str(conn.recv(1024), encoding='utf-8')

    print('Client message is:', clientMessage)

    serverMessage = 'I\'m here!'
    conn.sendall(serverMessage.encode())
    conn.close()



No output, because we just startup the server and port 8000 and we wait the client to send some message to server.


Client.py

import socket

HOST = '127.0.0.1'
PORT = 8000
clientMessage = 'Hello!'

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
client.sendall(clientMessage.encode())

serverMessage = str(client.recv(1024), encoding='utf-8')
print('Server:', serverMessage)

client.close()



Output:

# Server
Client message is: Hello!
# Client
Server: I'm here!

Explain a little:

When we started to set server, we need to set the host ip and our port to open. In here, we set the locale host: 127.0.0.1 (You can also instead of the localhost, use fixed ip if you want).

socket.AF_INET: IPv4 (Default)
socket.SOCK_STREAM: TCP (Default) 

And then we want to set these two options which are also classic IPv4 TCP/IP connections. This connection mechanism is relatively reliable, but the transmission speed is not fast enough.

By the way, the messages we send are "byte" data type, so we need to convert to "string" to display.

when the client send the message once, it will be shut down; The server will not, it still wait for another client.

The article is a basic introduction, the next article will be the application tutorial.

Leave a Reply