Last Updated:

Socket Programming in Python | With Examples

A web server is a server that provides information to the user at his request. Data exchange takes place via the HTTP protocol, which contains clauses of the agreement between the user and the server on data transfer.

Socket Programming in Python

A socket is a programming interface that is the connection point of the parties for exchanging data. It has certain content that can be extracted or replenished. Sockets have their own characteristics. One of the points is the version of the Internet Protocol. There are two of them: IPv4 and IPv6.

The second point of the characteristics of sockets is the type of data transfer and the protocol. At the same time, in one information data package there is a weight limit. Each packet is assigned a party address and a time.
When transferring data, information is likely to be lost or its integrity is violated. That is, the message may simply not come or not go, as well as come with a delay.

 

This can cause the sent message to become generally unreadable. To avoid such situations, NTTR works together with tcpr, a transmission control protocol. A connection is used to accomplish the goal. They contain information about the numbering of packets.

 

When sending messages from different connections, but from the same device, a division into ports was introduced. They are a set of numbers that is the address of the connection.

Python 3 Network Programming

 

To create a socket, use the socket.socket( ) function. Work with sockets can be carried out by applying functions to them, such as bind (communication with the port and name), listen (listening for the socket), accept (joining the user). A client can join a socket using the connect function.
To work with the socket, the constructs recv or recvfrom (receive), send or sendto (send), close (close the socket), as well as gethostname (get hostname) are also used.

Chat client/server

 

Using the Python programming language, you can create a client/server chat. At the same time, an unlimited number of users can join the chat. This program is suitable for instant messengers, game chats and other applications.

For the chat to work, you need at least two parts:

  • a server that will connect all connecting users,
  • at least one user.

Let's start writing a server. Initially, you need to create a programming interface (socket, socket), which will provide data exchange. This can be done using the importsocket construct. In the same line, separated by a comma, add time.

Then enter the variablehost, which indicates the IP address. This is necessary for the proper operation of the program when changing the geolocation.

Host=socket.gethostbyname (socket.gethostname( ))

To create a connection, you need to select a port. There are 65535 of them in total, but usually up to a certain figure they can only be used if you have root privileges. Let's take the port value to 11111.
Create an array that stores client addresses. We use the clients variable for clarity.

Clients= [ ]

Sockets can be client and server. A client socket connects to the server socket. Data is exchanged through the established connection. Let's create a variable: sock = socket.socket(). In parentheses, separated by commas, indicate the version of the Internet protocol and the type of socket (socket.AF_INET, socket. SOCK_DGRAM).

Declare the socket to be created. The server on the selected port will run on the specified host.

Sock.bind((host, port)).

Enter a variable denoting false. It is used to end the program cycle. This will happen when the variable signifying truth becomes equal to lies. The loop will stop and the server will stop working.

F=false

To indicate the beginning of the loop, display the started label.

Print(‘[ Started ]’)

Now let's denote the main body of the program. It will be the loop specified by the while.

WhilenotF:

Then, we will describe the try and except blocks in sequence. These constructs are related because if a program finds an exception to the condition of the try block, it acts on the except block.

In the try part, enter two equivalent date and address variables, denote the message, address. The latter means the user's address, and the first is the text of the message with the sender's nickname. Assign these variables a socket value with the recvfrom( ) function. In parentheses, indicate the weight of the file. The base value is 1024 bytes.

Try:

Message, address = sock.recvfrom (1024)

Next is the customer address recognition string. If it is new, the address is entered into the Clients array.

If address not in Clients:
Clients.append(address)

In instant messengers, the time of sending messages or notifications about the accession of new participants or the exit of old ones is usually indicated. To do this, enter the variable T. In its value, specify the year, month, day, hour, minute, second. To do this, we use the strftime and localtime constructs.

T=time.strftime(‘ %y-%m-%d-%h.%M.%s ’, time.localtime())

To make all this visible on the server, output the data using the print function and decrypt the message encoded in 8-bit form.

Print( ‘[‘+address[0]+’]=[‘+str(address[1])+’]=[‘+T+’]/’, end=’ ’ )
Print (massage.decode( ‘utf-8’ ))

Also, the sender should not receive their own message. To do this, use a for loop. That is, the user who sent the message will not be shown again.

For client in Clients:
If address! =client:
Sock.sendto (message, client)

Now let's describe the exception. If an error occurs in the program (for example, quitting the program). We write this part in the except section. To indicate the end of the server, we will display the inscription Stopped.

Print (‘\n[ Stopped ]’)
F=true

The last, final deadline in the server program is the closure of the socket.

Sock.close()

Next, you need to write a client program. Its structure is similar to a server, but it is more complex. The first line is also executed using the import function, but a threading module is added to socket and time. It is needed so that the user can receive messages immediately. Without this module, the program would show a new message only after sending a response. So, the convenience and meaning of the messenger is lost.

Importsocket, time, threading

Now you need to add a variable that will be used as a key to encode the data.

Key=8194

Enter two variables that mean false.

Out=false
join=false

Next, declare the function to be the def construct. The declared function will be receiving( ), in parentheses specify the name and socket. It will allow you to receive messages. After the colon, a system of cycles is built. Let's start with the while loop, the condition will be the unequal Cut. After this line, we branch into try andexcept. After try, write another while loop, where the condition is to set the cut's inequality to the truth (true). Then we copy the stock from the server code with the user's address and a message where the weight of the file to be sent is indicated.

Defreceiving (name, sock):
While not Cut:
Try:
While true:
Message, address = sock.recvfrom (1024)

The next step is to decrypt the messages. To do this, we use the decrypt construct.

Decrypt = ‘ ’; k = false
For i in massage.decode(‘utf-8’):
If i==’:’:
K=true
Decrypt +=i
Elif k== false or i==’ ’:
Decrypt +=i
Else:
Decrypt +=chr(ord(i)’Key)
Print(decrypt)

You also need to enter a string with a delayed time output using the sleep construct.

Time.sleep(0.5)

In the extend part that follows, there will be only one line, indicating that the error that occurred was missed.

Except:
pass

Now enter the host and port variables. In the host value, duplicate the drain that was used in the server code.Port is set to 0, because the client does not create a network, it connects to it. That is, there is no need to choose a port. You must also specify the server and its port number.

Host=socket.gethostbyname (socket.gethostname ( ))
Port=0
Server= (‘184.155.0.112’, 11111)

Now enter the variable repeat the variable sock, which was written in the server code.Also repeat the next line. This feature works with the host and port values. The following line is required to be able to leave the chat (close the window). Without the setblocking function, all user actions will be accompanied by various system errors.

Sock = socket.socket (socket.AF_INET, socket. SOCK_DGRAM).
Sock.bind ((host, port)).
Sock.setblocking(0)

The user must have a name. To do this, create a nickname variable that will be displayed when the user sends messages. The input() function allows the user to enter the desired nickname from the keyboard.

Nickname = input(‘Name: ’)

Now we work with the threading function. Create an eT variable and assign it a threading processing value with the Thread( ). In parentheses, insert a target equal to receiving. With a comma, we indicate the operation of the program by the args construct through the sock variable. Run the variable.

eT=threading. Tread(target=receiving, args-(‘RechThread’, sock))
eT.start( )

Now describe the while loop through the equivalence of the Outlzhi variable. Branch the cycle on if ielse. In the if part, set the condition to join=false. Then the program performs a send operation on the sock variable. Thus, the user's name and information about its accession will be displayed on the server.In the same line, add a decryption of the encoded message.Now join is true.

While Out==false:
If join==false:
Sock.sendto((‘[‘+nickname+ ‘]=> join massager’).encode(‘utf-8’), server)
Join=true

Also describe the branching else. This part means join==true. Use the try and except function. The first function is followed by sending a message.

Else:
Try:
Massage=input( )

Next, encrypt the message.

Crypt= ’ ’
For I in massage:
Crypt += chr(ord(i)’Key)
Massage=crypt

Next is the if loop, where a message without content is not sent to the chat.

If massage !=’ ‘:
Sock.sendto((‘[‘+nickname+’]::’+massage).encode(‘utf-8’), server)

Now, the message should have a time to send. To do this, use the sleep function, which will highlight the time with a slight delay, which we indicate in parentheses.

Time.sleep(0.5)

Enter the except loop to resolve errors. That is, when closing the program, we display an inscription in the chat about the user's exit, decode. The Out variable is now true. Close the program.

Except:
Sock.sendto((‘[‘+nickname+’]=>leftmessenger’).decode(‘utf-8’), server)
Cut=true
eT.join( )
sock.close( )

CGI: Website in python 3HelloWorld

CGI is a protocol that transmits and receives data. With its help, we will create a simple site.

from http.serverimportHTTPServer, CGIHTTPRequestHandler
server_address = (‘‘, 8000)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()

This code will add a site with a http://localhost:8000 address to your browser.

Next, we proceed to write the site. The first line will simply output the text. The file will be html, which is reflected in the first line of code. The second displays the necessary inscription.

 

print(«Content-type: text/html»)
print(«<h1>Hello World!</h1>»)

On the link http://localhost:8000/cgi-bin/hello.py will be the simplest site with just one inscription: HelloWorld!