树莓派与PC端在局域网内运用python实现即时通讯

时间:2022-09-07 17:54:40

电脑和树莓派在同一局域网内,先在电脑和树莓派创建python运行环境,然后在树莓派中用python运行rpi.py;在电脑上运行computer.py;电脑上输入字符即可在树莓派上即时显示!

rpi.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。