Abstract: This article covers all areas of socket programming using Python. Sockets help you establish these connections, and Python certainly simplifies connections.

This article to share from huawei cloud community “from scratch to learn python | what is in python socket programming and how to master it?” , original author: Yuchuan.

It is undeniable that the Internet has become the “soul of existence”, whose activities are characterized by “connection” or “network”. The use of sockets is one of the most critical foundations that makes these networks possible. ** This article covers all areas of socket programming using Python. Sockets help you establish these connections, and Python certainly simplifies connections.

Let’s take a quick look at all the topics covered in this article:

Why use Sockets?

What are Sockets in Python?

How to achieve Socket Programming in PythonWhat is a server?

What is a client?

Echo Client-Server

Multiple Communications

Transferring Python Objects

  • Python pickle module
  • How to transfer python objects using the pickle module

Why use Sockets?

Sockets are the foundation of the network. They make it possible to transfer information between two different programs or devices. For example, when you open a browser, you, as the client, are establishing a connection to a server for information transfer.

Before delving into this communication, let’s be clear about exactly what these sockets mean.

What are Sockets?

In general, a socket is an internal endpoint built to send and receive data. A single network will have two sockets, one for each communication device or program. These sockets are a combination of IP addresses and ports. Depending on the port number used, a single device can have n slots. Different ports can be used for different types of protocols. See the following image to learn more about some common port numbers and related protocols:

Now that you understand the concept of sockets, let’s take a look at Python’s Socket module:

How to implement Socket programming in Python:

To implement Socket programming in Python, you will need to import the Socket module or framework. This module consists of the built-in methods needed to create sockets and help them relate to each other.

Some important methods are as follows:

Now that you understand the importance of the socket module, let’s move on to look at how it creates servers and clients for socket programming in Python.

What is a server?

A server can be a program, a computer, or a device dedicated to managing network resources. The server can be on the same device or computer, connected locally to other devices and computers, or even connected remotely. There are various types of servers, such as database server, network server, print server, etc.

The server usually uses methods such as socket.socket (), socket.bind (), socket.listen () to establish connections and bind them to the client. Now, let’s write a program to create a server. Consider the following example:

Example:

import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),1234))          
#port number can be anything between 0-65535(we usually specify non-previleged ports which are > 1023)
s.listen(5)
 
while True:
    clt,adr=s.accept()
    print(f"Connection to {adr}established")  
   #f string is literal string prefixed with f which 
   #contains python expressions inside braces
    clt.send(bytes("Socket Programming in Python","utf-8 ")) #to send info to clientsocket
Copy the code

As you can see, the first requirement for creating a socket is to import the socket module. After that, the server-side socket is created using the socket.socket () method.

NOTE:

AF_INET is an address on the Internet, and it requires a pair (host, port) where the host can be the URL of a particular web site or its address, and the port number is an integer. SOCK_STREAM is used to create TCP.

The bind () method takes two arguments as a tuple (host, port). However, it is best to use 4-digit port numbers because smaller port numbers are usually used. The Listen () method allows the server to accept connections. In this case, 5 is a queue of multiple connections appearing simultaneously. The minimum value you can specify here is 0 (if you provide a smaller value, change it to 0). If no parameters are specified, the default appropriate parameters are used.

The while loop allows accepting connections forever. “CLT” and “ADR” are client objects and addresses. The print statement prints only the address and port number of the client socket. Finally, clt.send is used to send bytes of data.

Now that our server is ready, let’s move on to the client side.

What is a client?

A client is a computer or software that receives information or services from a server. In the client server module, the client requests services from the server. The best examples are Web browsers, such as Google Chrome, Firefox, etc. These Web browsers request required pages and services from the Web server as indicated by the user. Other examples include online games, online chatting, etc.

Now let’s look at how to write a client program in the Python programming language:

Example:

import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 2346))
msg=s.recv(1024)
print(msg.decode("utf-8"))
Copy the code

The first step is to import the socket module, and then create the socket just as you created the server. Then, to create a connection between client and server, you need to use the connect () method by specifying (host, port).

Note: GethostName is used when the client and server are on the same computer. (LAN – Local IP/WAN – public IP)

Here, the client wants to receive some information from the server, for which you need to use the recv () method and store that information in another variable MSG. Keep in mind that the information passed will be in bytes, and in the client side of the above program, a transfer can receive up to 1024 bytes (buffer size). Any number can be specified, depending on the amount of information transferred.

Finally, the message being transmitted should be decoded and printed.

Now that you know how to create client-server programs, let’s move on and see how to execute them.

Echo Client-Server:

To execute these programs, open a command prompt, go to the folder where you created the client and server programs, and type:

Py server.py (in this case, server.py is the file name of the server, you can also use py-3.7 server.py)

When this is done, the server will be running. To execute the client, open another CMD window and type:

Py client.py (where client.py is the file name of the client)

Output (server) :

(the customer)

Let’s try the same program by reducing the buffer size to 7, and see what output we get:

Output:

As you can see, the connection terminates after seven bytes have been transferred. This is a problem, however, because you have not received the complete information and the connection is closed. Let’s get on with it.

Multiple Communications:

To keep the connection going until the client receives the complete information, use the while loop:

Example:

import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 2346))
while True:
msg=s.recv(7)
print(msg.decode("utf-8"))
Copy the code

When this is done, the complete message will be received in seven bytes per transfer.

But this time, as you can see, the connection does not terminate, and you do not know when the connection will occur. Beyond that, what if you don’t actually know how big a message or information the client will receive from the server. In this case, you can actually use the following code on the client side:

Example:

complete_info=''
while True:
    msg = s.recv(7)  
    if len(msg)<=0:
        break
    complete_info += msg.decode("utf-8")
print(complete_info)
Copy the code

On the server side, use the close () method as follows:

clt.close()
Copy the code

The output is shown below:

Output:

All the above code block does is check the size of the information, print it out in a two-byte buffer at a time, and close it when the connection is complete.

Transferring Python objects:

Until now, you have the knack of transferring strings. However, socket programming in Python also allows you to transfer Python objects. These objects can be collections, tuples, dictionaries, anything. To do this, you’ll need to import Python’s pickle module.

Python pickle module:

The Pythonpickle module appears when you actually serialize or deserialize objects in Python. Let’s look at a small example

Example:

Import pickle mylist=[1,2,' ABC '] mymsg = pickle.dumps(mylist) print(mymsg)Copy the code

Output: b ‘x80x03] qx00 (Kx01Kx02Xx03x00x00x00abcqx01e.

As you can see, in the program above, ‘myList’ is serialized using the dumps () function of the pickle module. Also note that the output begins with a “b,” which means it has been converted to bytes. In socket programming, you can implement this module to transfer Python objects between clients and servers.

How do I pass Python object structures using the pickle module?

When you use pickles with sockets, you can transfer absolutely anything over the network. Let’s write down the server-side and client-side counterparts to transfer the list from the server to the client:

Server side:

import socket
import pickle
 
a=10
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 2133))        #binding tuple
s.listen(5)
while True:
    clt , adr = s.accept()
    print(f"Connection to {adr}established")
 
    m={1:"Client", 2:"Server"}
    mymsg = pickle.dumps(m)  #the msg we want to print later
    mymsg = {len(mymsg):{a}}"utf-8") + mymsg
    clt.send(mymsg)
Copy the code

In this case, M is a dictionary, which is basically a Python object that needs to be sent from the server to the client. This is done by first serializing objects with dumps () and then converting them to bytes.

Now let’s write the corresponding content for the client:

Client:

import socket import pickle a=10 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((socket.gethostname(), 2133)) while True: complete_info = b'' rec_msg = True while True: mymsg = s.recv(10) if rec_msg: print(f"The length of message = {mymsg[:a]}") x = int (mymsg[:a ] ) rec_msg = False complete_info += mymsg if len(complete_info)-a == x: print("Recieved the complete info") print(complete_info[a:]) m = pickle.loads(complete_info[a:]) print(m) rec_msg = True  complete_info = b'' print(complete_info)Copy the code

The first while loop will help us keep track of the complete message (complete_info) as well as the message being received using the buffer (rec_msg). Set the message by setting rec_, and then, when receiving the message, all I do is print each message and receive it in a buffer of size 10. This size can be any value, depending on your personal choice. Then, if the received message is equal to the complete message, I just print the message as the received complete message and then use loads () to deserialize the message.

The output of the above program is as follows:

This brings us to the end of this article about programming with sockets. Hopefully you have a clear understanding of all the concepts.

Click to follow, the first time to learn about Huawei cloud fresh technology ~