服务器之家

服务器之家 > 正文

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

时间:2021-07-18 14:58     来源/作者:XC2439

电脑和树莓派在同一局域网内,先在电脑和树莓派创建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)

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

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部