Python provides socket modules for accessing network services, enabling processes between different hosts to communicate with each other


1. Create the Socket object

socket.socket([family[, type[, proto]]])
Copy the code
  • Family: indicates the socket family. The values are as follows:

    • socket.AF_INET: Network communication between different hosts using IPV4
    • socket.AF_INET6: Uses IPV6 for network communication between different hosts
    • socket.AF_UNIX: Communicates with processes on the same host
  • Type: indicates the socket type. The value can be:

    • socket.SOCK_STREAM: stream socket for TCP communication
    • socket.SOCK_DGRAM: datagram socket for UDP communication
    • socket.SOCK_RAW: Raw socket, used to process special network packets such as ICMP and IGMP
  • Proto: indicates the protocol number. The default value is 0

2, Socket object common methods

(1) Common methods of the server

  • bind(address): Binds the address to the socket. Address represents the communication address. The format depends on the socket family used
  • listen(backlog)Backlog represents the maximum number of connections that can be suspended before they are rejected
  • accept(): Accepts the connection and returns(conn, address)Conn is the new Socket object used to receive and send data

(2) Common methods of the client

  • connect(address): Connects to the socket at the specified address and returns if the connection failssocket.error
  • connect_ex(address): Connects to a socket at the specified address, and returns an error code if the connection fails

(3) Common methods for public use

  • close(): Closes the socket
  • recv(bufsize[,flag]): Receives data, generally used over TCP, and returns the received data
  • recvfrom(bufsize[,flag]): Receives data, generally used over UDP, and returns the received data and the address of the sender
  • send(data[,flag]): Indicates the number of bytes sent. This parameter is used for TCP
  • sendto(data[,flag],address): Indicates the number of bytes sent. This parameter is used for UDP
  • getsockname(): returns the address of the connected socket
  • getpeername(): Returns the remote address of the connection socket
  • getsockopt(level,optname): Gets socket options
  • setsockopt(level,optname,value): Sets socket options
  • gettimeout(): Gets the timeout value for the socket, or None if no timeout is set
  • settimeout(timeout): Sets the timeout value of the socket. Timeout indicates the timeout period, in seconds

Example 3,

(1) The client transmits data to the server

# server.py

import socket
import threading

def create_service() :
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    address = ('127.0.0.1'.8888)
    server.bind(address)
    server.listen(5)
    print('Waiting connection ... ')
    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target = handle_request, args = (conn, addr))
        thread.start()
    server.close()

def handle_request(conn, addr) :
    print('Accept connection from', addr)
    while True:
        recv_byte = conn.recv(1024)
        recv_data = recv_byte.decode('UTF-8')
        print(recv_data)
        if recv_data == 'quit': break
    conn.close()

if __name__ == '__main__':
    create_service()
Copy the code
# client.py

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = ('127.0.0.1'.8888)
client.connect(address)
print('Connect to', address)

while True:
    send_data = input('Please Enter Something: ')
    send_byte = send_data.encode('UTF-8')
    client.send(send_byte)
    if send_data == 'quit': break

client.close()
Copy the code

(2) The client downloads files from the server

# server.py

import socket
import threading
import os
import json

def create_service() :
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    address = ('127.0.0.1'.8888)
    server.bind(address)
    server.listen(5)
    print('Waiting connection ... ')
    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target = handle_request, args = (conn, addr))
        thread.start()
    server.close()

def handle_request(conn, addr) :
    print('Accept connection from', addr)
    while True:
        file_name = conn.recv(1024).decode('UTF-8')
        print('Request File:', file_name)
        if not os.path.exists(file_name):
            message = 'Not Exist'
            print(message)
            conn.send(message.encode('UTF-8'))
        else:
            real_name = os.path.split(file_name)[1]
            file_size = os.path.getsize(file_name)
            file_info = json.dumps({
                'real_name': real_name,
                'file_size': file_size
            })
            conn.send(file_info.encode('UTF-8'))
            conn.recv(1024)
            print('Send File ... ')
            with open(file_name, 'rb') as file:
                for line in file:
                    conn.send(line)
                print('Send File Successful')
    conn.close()

if __name__ == '__main__':
    create_service()
Copy the code
# client.py

import socket
import os
import json

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = ('127.0.0.1'.8888)
client.connect(address)
print('Connect to', address)

while True:
    file_name = input('Please Enter File Name: ')
    client.send(bytes(file_name, encoding='UTF-8'))
    recv_data = client.recv(1024).decode('UTF-8')
    if recv_data == 'Not Exist':
        print(recv_data)
    else:
        file_info = json.loads(recv_data)
        real_name = file_info['real_name']
        file_size = file_info['file_size']
        client.send(bytes('Received', encoding='UTF-8'))
        print('Receive File ... ')
        recv_size = 0
        with open(real_name, 'wb') as file:
            while recv_size < file_size:
                chunk = client.recv(1024)
                file.write(chunk)
                recv_size += len(chunk)
            print('Receive File Successful')

client.close()
Copy the code

(3) The client uploads files to the server

# server.py

import socket
import threading
import os
import json

def create_service() :
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    address = ('127.0.0.1'.8888)
    server.bind(address)
    server.listen(5)
    print('Waiting connection ... ')
    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target = handle_request, args = (conn, addr))
        thread.start()
    server.close()

def handle_request(conn, addr) :
    print('Accept connection from', addr)
    while True:
        recv_data = conn.recv(1024).decode('UTF-8')
        file_info = json.loads(recv_data)
        real_name = file_info['real_name']
        file_size = file_info['file_size']
        conn.send(bytes('Received', encoding='UTF-8'))
        print('Receive File ... ')
        recv_size = 0
        with open(real_name, 'wb') as file:
            while recv_size < file_size:
                chunk = conn.recv(1024)
                file.write(chunk)
                recv_size += len(chunk)
            print('Receive File Successful')
    conn.close()

if __name__ == '__main__':
    create_service()
Copy the code
# client.py

import socket
import os
import json

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = ('127.0.0.1'.8888)
client.connect(address)
print('Connect to', address)

while True:
    file_name = input('Please Enter File Name: ')
    if not os.path.exists(file_name):
        print('Not Exist')
        continue
    real_name = os.path.split(file_name)[1]
    file_size = os.path.getsize(file_name)
    file_info = json.dumps({
        'real_name': real_name,
        'file_size': file_size
    })
    client.send(file_info.encode('UTF-8'))
    client.recv(1024)
    print('Send File ... ')
    with open(file_name, 'rb') as file:
        for line in file:
            client.send(line)
        print('Send File Successful')

client.close()
Copy the code