Raspberry Pie Network Socket (Python edition) __python

Source: Internet
Author: User

I used the socket on my computer to communicate between two programs, and this time we used the same program to communicate between the raspberry and the computer.

First look at the program, the specific interpretation of the program can see my last blog

This time the only difference is the host to 192.168 or something, their own in the DOS interface knock ipconfig check the IP address and fill in

Server End:

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 (  
        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 in the DOS interface and run client.py in the raspberry pie.

Notice that the Python3 command is used in the raspberry pie because the raspberry pie has both python2 and Python3

DOS interface:


Raspberry pie:



If we want to run the client side on a raspberry-run server-side computer and have the raspberry sent as a server to receive user data, we can ifconfig the raspberry pie to see its address and change the IP address of the two programs to it. Then run the server on the raspberry pie and run the client on the computer.

If you want to implement UDP transmission, you can put my last blog's UDP code to modify the next try, because the specific I have not tried hehe

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.