python下两台电脑的socket通信,及将主机收到数据做ROS主题形式发布,远程电脑通过wifi订阅发布数据
1. python下客户端程序编写(无ros)
vim ~/python_ex/test_tcp_client.py
#!/usr/bin/python
import time
import socket
#设置服务器ip地址,端口,buffer容量
HOST='192.168.2.4'
PORT=8008
BUFFER=4096
while 1:
#定义socket通信类型 ipv4,tcp
soc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#连接服务器
soc.connect((HOST,PORT))
#延时
time.sleep(1)
#发送消息
soc.send('hello ros')
#接受消息
buf=soc.recv(BUFFER)
打印消息
print(buf)
#接口关闭
soc.close()
2. firefly主板中的服务器编写(ros节点格式)
catkin_creat_pkg tcp2ros rospy roscpp std_msgs message_generation
vim ~/joey/src/tcp2ros/src/tcp2rostalker.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import socket
import rospy
from std_msgs.msg import String
######################tcp begining
HOST='192.168.2.4'
PORT=8008
BUFFER=4096
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((HOST,PORT))
sock.listen(5)
################ros begining
rospy.init_node('tcptalker',anonymous=0)
pub=rospy.Publisher('tcptopic',String,queue_size=10)
print 'i am listening'
while not rospy.is_shutdown():
con,addr=sock.accept()
try:
con.settimeout(5)
buf=con.recv(BUFFER)
pub.publish(buf)
time.sleep(1)
except socket.timeout:
print 'time out'
con.send('yes i recv')
con.close()
3. 多服务器ros配置
3.1 firefly下
vim /etc/hosts
192.168.20.133 firefly (本机ip)
192.168.20.135 LT-0079 (服务器IP)
vim ~/bashrc -->添加
export ROS_HOSTNAME=firefly
export ROS_MASTER_URI=http://LT-0079:11311
---------------------------
3.2 服务器下
vim /etc/hosts
192.168.20.133 firefly
192.168.20.135 LT-0079
vim ~/bashrc -->添加
export ROS_HOSTNAME=firefly
export ROS_MASTER_URI=http://LT-0079:11311
4 程序运行
chmod +x ~/joey/src/tcp2ros/src/tcp2rostalker.py
cd ~/joey |catkin_make
- 服务器中
rosocre
rostopic echo /tcpros
- firefly中
rosrun tcp2ros tcp2rostalker.py
- 单片机客户端中
python tcp_client.py