python局域网通信_树莓派与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)

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

您可能感兴趣的文章:使用Python的Django和layim实现即时通讯的方法

Python基于socket实现简单的即时通讯功能示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值