Python network programming: Implementing a simple socket server

王林
Release: 2023-06-18 08:47:33
Original
3230 people have browsed it

Python is a very popular programming language. It contains many powerful libraries and tools that can be used to perform a variety of programming tasks, including network programming. Python provides many libraries and tools for writing web applications. The most commonly used one is the socket library.

This article will introduce how to use the Python socket library to write a simple socket server. We will explain in detail the concept of socket, the implementation process of socket server, and provide code examples.

1. Socket concept

Socket is an abstraction layer used to communicate in the network. It is implemented based on the TCP/IP protocol stack. Simply put, Socket is an interface for communication on the network, which allows communication between two applications on the network.

Socket can usually be divided into two parts: one is the server side and the other is the client side. The server is a program that listens to a certain port on the network and waits for the client's connection request; the client is the program that initiates a connection request to the server. Once the client and server have established a connection, they can transmit data over the network.

2. Socket server implementation

We will first implement a simple socket server. The server will listen on a port number and wait for client connection requests. Once the connection is established, the server accepts messages sent by the client and prints them to the console.

Step 1: Create a Socket server

We can use the Python socket library to create a server socket. The server socket is bound to the specified port and IP address and listens for client connection requests.

import socket

HOST = '127.0.0.1'
PORT = 5555

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(1)
print('Waiting for connection...')
Copy after login

In this code snippet, we first create a socket object and bind it to the specified IP address and port number. Then we called the listen() method to wait for the client's connection request. At this point the server is ready to accept the client's request.

Step 2: Wait for client connection

Once the server is ready to accept client connections, we can use the accept() method to wait for the arrival of client requests. If a client requests a connection, the accept() method will return a new socket object, which can be used to communicate with the client.

while True:
    client_socket, addr = server_socket.accept()
    print('Connection from:', addr)
Copy after login

In this code snippet, we use a while loop to wait for the client to connect. When the client requests a connection, the accept() method will return a new socket object and the client's IP address and port number. We call the new socket object the client socket and print out the client's address information.

Step 3: Communicate with the client

Once the connection is established with the client, we can use the recv() method to receive the data sent by the client and then print it in the console.

while True:
    client_socket, addr = server_socket.accept()
    print('Connection from:', addr)

    while True:
        data = client_socket.recv(1024)
        if not data:
            break
        print('Received message:', data.decode())

    client_socket.close()

server_socket.close()
Copy after login

In this code snippet, we first establish a connection with the client and traverse to receive all messages from the client. We use the recv() method to receive the data sent by the client and print it on the console. If the client does not send any data, we exit the inner loop and close the client socket.

Finally, we need to close the server socket.

3. Complete code example

import socket

HOST = '127.0.0.1'
PORT = 5555

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(1)
print('Waiting for connection...')

while True:
    client_socket, addr = server_socket.accept()
    print('Connection from:', addr)

    while True:
        data = client_socket.recv(1024)
        if not data:
            break
        print('Received message:', data.decode())

    client_socket.close()

server_socket.close()
Copy after login

4. Summary

In this article, we explain the use of the Python socket library, introduce the concept of socket, and how to use Python The socket library implements a simple socket server. I hope this article can help readers understand the implementation principles of sockets and provide some help for readers when using Python for network programming.

The above is the detailed content of Python network programming: Implementing a simple socket server. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template