Chapter 1.19 network programming basis

1, socket programming

  • Socket is also called socket
  • Socket programming is actually to use code to realize two ends of network communication; socket is to realize two programs of communication
  • The two ends of communication are divided into server and client
  • python provides classes and methods related to socket programming through socket module

2, Server side

(Note: in the following operations, the server and client are implemented in two py files)

1. Create socket object (buy phone)

socket(family=AF_INET, type=SOCK_STREAM)

family - Set up ip type; AF_INET The corresponding is ipv4; AF_INET6 The corresponding is ipv6
type - Set transfer type;  SOCK_STREAM The corresponding is TCP Agreement; SOCK_DGRAM The corresponding is UDP Agreement

2. Bind IP and port (plug in telephone line)

bind((ip address, port))

ip address: find the only computer in the Internet; assign the string corresponding to the ip address
 Port: distinguish different services (programs) in the same computer; assign an integer with a value range of 0-65535, of which 0-1024 is famous and cannot be used casually.
     The same port can only correspond to one service at the same time

3. Start monitoring (waiting for the phone)

server.listen(N)

N : Indicates that it can be connected at the same time"Telephone"Quantity

4. Accept the client request (answer the phone)

connection, address = server.accept()

connection: the extension object of the client received by the server
 Address: the IP address of the client
 Returns the independent socket object (extension) created for this client and the address of the client
 When the program runs to this code, it stops until there is a request

5. Receive the message (listen to the other party)

Extension object. Recv (the size of data that can be received at one time)

Returns the received data. The data type is binary

6. Send message (speak to others)

Extension object. Send (data to be sent)

7. Close the connection (hang up)

Extension object. close()

A complete server

from socket import socket

server = socket()
server.bind(('192.168.10.234', 5200)) # IP address can use the IP address of your own computer, and the port is arbitrary, as long as it is not 0-1024
server.listen(50) # Indicates that the server can communicate with 50 clients at the same time
while True: # Keep the call going
    print('Monitoring...')
    connection, address = server.accept() # Accept the client request, create the extension object connection, and return the extension address
    recv_data = connection.recv(1024).decode(encoding='utf-8') # Receives data from the client and converts the binary to a string (. decode method)
    print('recv_data') # Print received data
    massage = input('Please enter the content to send:') # Enter what to send
    connection.send(massage) # send data
    connection.close() # Close dialogue

3, Client

1. Create socket object (buy phone)

client = socket()

2. Connect to the server

client.connect(('192.168.10.234', 5200))

3. Send message

client.send()

4. Receive message

client.recv()

5. Disconnect

client.close()

A complete client

client = socket()
client.connect(('192.168.10.234', 5200))
client.send('How is the server?'.encode())
re_data = client.recv(1024)
print(re_data.decode(encoding='utf-8'))
client.close()

4, Other operations

1. One to one continuous communication

"""Server side"""
from socket import socket

server = socket()
server.bind(('10.7.156.55', 9999))
server.listen(20)
while True:
    print('Monitoring...')
    connection, address = server.accept()
    # Continuous communication
    while True:
        re_data = connection.recv(1024)
        re_massage = re_data.decode(encoding='utf-8')
        print('client:', re_massage)
        if re_massage == 'Bye':
            connection.close()
            break

        massage = input('server:')
        connection.send(massage.encode())
        if massage == 'Bye':
            connection.close()
            break


"""Client"""
from socket import socket

client = socket()
client.connect(('10.7.156.55', 9999))
while True:
    massage = input('client:')
    # for _ in range(10):
    client.send(massage.encode())
    if massage == 'Bye-bye':
        client.close()
        break

    re_massage = client.recv(1024).decode(encoding='utf-8')
    print('server:', re_massage)
    if re_massage == 'Bye-bye':
        client.close()
        break

2. Send pictures

"""Server side"""
from socket import socket

server = socket()
server.bind(('10.7.156.55', 8000))
server.listen(1024)
while True:
    connection, address = server.accept()
    with open('../code/1024x1024.jpg', 'rb') as f:
        data = f.read()
    connection.send(data)


"""Client"""
from socket import socket

client = socket()
client.connect(('10.7.156.55', 8000))
# Received picture length
total_length = int(client.recv(1024).decode())
print('For the first time:', total_length)
sum_data = bytes()   # Save the total data of received pictures
# Receiving pictures
while True:
    re_data = client.recv(1024)
    sum_data += re_data
    if len(sum_data) == total_length:
        with open('client/test1.wav', 'wb') as f:
            f.write(sum_data)
        break

End of the flower

Published 20 original articles, praised 0, visited 89
Private letter follow

Tags: socket encoding Programming network

Posted on Wed, 11 Mar 2020 07:04:54 -0400 by tsigo