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

发布时间:2020-09-28 06:20:23 作者:XC2439
来源:脚本之家 阅读:538

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

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

推荐阅读:
  1. 局域网内用户私自接无线AP
  2. 局域网内命令大全

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 即时通讯

上一篇:微信小程序获取手机号授权用户登录功能

下一篇:django_orm查询性能优化方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》