Raspberry Pi network socket (python version)

Previously, I used socket to communicate between two programs on the computer. This time we still use the same program to communicate between the Raspberry Pi and the computer.

Look at the program first, the specific analysis of the program can be found in my last blog

The only difference this time is that the HOST is changed to 192.168 or something. You can tap ipconfig on the dos interface to check the IP address and then fill it in.

server side:

import socket
import time

HOST = '192.168.199.131'
PORT = 8001
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)  
sock.bind((HOST, PORT))  
sock.listen(5)  
while True:  
    connection,address = sock.accept()  
    try:  
        connection.settimeout(10)  
        buf = connection.recv(1024)  
        if buf:  
            connection.send(b'welcome to server!')
            print('Connection success!')
        else:  
            connection.send(b'please go out!')  
    except socket.timeout:  
        print ('time out')
    connection.close()  

client side:
import socket
import time

HOST = '192.168.199.131'
PORT = 8002
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)  
sock.connect((HOST, PORT))  
time.sleep(2)  
sock.send(b'1')
print (sock.recv(1024).decode())
sock.close()  


Then run server.py on the dos interface and client.py on the Raspberry Pi

Note that you have to use the python3 command in the raspberry pi, because the raspberry pi has both python2 and python3

dos interface:


raspberry pie:



If we want to run the client on the computer running the server on the Raspberry Pi, and let the Raspberry Pi serve as the server to receive user data, we can check its address with ifconfig on the Raspberry Pi, and put the two programs Change the IP address to it, then run the server on the Raspberry Pi first and then run the client on the computer.

If you want to implement UDP transmission again, you can copy the UDP code of my last blog and try it, because I haven't tried it yet.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325617117&siteId=291194637