树莓派与PC端在局域网内运用python实现即时通讯
电脑和树莓派在同一局域网内,先在电脑和树莓派创建python运行环境,然后在树莓派中用python运行rpi.py;在电脑上运行computer.py;电脑上输入字符即可在树莓派上即时显示!
rpi.py
#coding:utf-8 #import necessary package import socket import time import sys HOST_IP = "192.168.31.151" #树莓派的IP地址 HOST_PORT = 8888 print("Starting socket: TCP...") #1.create socket object:socket=socket.socket(family,type) socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT) ) host_addr = (HOST_IP, HOST_PORT) #2.bind socket to addr:socket.bind(address) socket_tcp.bind(host_addr) #3.listen connection request:socket.listen(backlog) socket_tcp.listen(1) #4.waite for client:connection,address=socket.accept() socket_con, (client_ip, client_port) = socket_tcp.accept() print("Connection accepted from %s." %client_ip) socket_con.send("Welcome to RPi TCP server!") print("Receiving package...") ###主循环 while True: try: data=socket_con.recv(512) if len(data)>0: print("Received:%s"%data) socket_con.send(data) time.sleep(1) continue except Exception: socket_tcp.close() sys.exit(1)
computer.py
import socket import time import sys SERVER_IP = "192.168.31.151" #树莓派的IP地址 SERVER_PORT = 8888 print("Starting socket: TCP...") server_addr = (SERVER_IP, SERVER_PORT) socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: print("Connecting to server @ %s:%d..." %(SERVER_IP, SERVER_PORT)) socket_tcp.connect(server_addr) break except Exception: print("Can't connect to server,try it latter!") time.sleep(1) continue print("Please input:") while True: try: data = socket_tcp.recv(512) if len(data)>0: print("Received: %s" % data) command=raw_input() socket_tcp.send(command) time.sleep(1) continue except Exception: socket_tcp.close() socket_tcp=None sys.exit(1)
相关推荐
LeeHDsniper 2020-11-05
橄榄 2020-11-03
wanshiyingg 2020-09-29
andonliu 2020-09-03
嵌入式开发爱好者 2020-08-28
lu00kill 2020-08-17
tianyayi 2020-08-16
LIEVEZ 2020-08-09
ohhardtoname 2020-07-25
LeeHDsniper 2020-07-19
shenxiuwen 2020-07-16
wzxxtt0 2020-06-25
mattraynor 2020-06-25
咏月东南 2020-06-10
wangz 2020-06-03
wanxuncpx 2020-06-01
tianyayi 2020-05-18
wanxuncpx 2020-05-15
mattraynor 2020-05-12
wzxxtt0 2020-05-12
LIEVEZ 2020-05-04
mattraynor 2020-05-01
LIEVEZ 2020-05-01
LIEVEZ 2020-05-01
LowisLucifer 2020-04-23
OathKeeper 2020-04-22
zcabcd 2020-04-18
wanxuncpx 2020-04-16
returnspace 2020-04-16
mattraynor 2020-04-14
tianyayi 2020-03-28
clamzxf 2020-03-28
Summer的小屋 2020-03-26
lu00kill 2020-03-17
yuancr 2020-03-04
wzxxtt0 2020-02-21
xinhao 2020-02-20
LIEVEZ 2020-02-17
wzxxtt0 2020-02-15
zhufu 2020-02-10