Plant Simulation之Socket通讯-v2
这篇文章主要写Plant simulation与python进行通讯。
(1)plant作为服务器
1)选择打开,并定义好IP地址和端口号
2)定义回调方法self.callback1
param channelNo: integer, message: string
print message
我这里仅在控制台打印python客户端传输过来的信息。
3)定义向python客户端发送信息的方法
var str:Integer:=1000000
Socket1.write(0,to_str(str+1))
print "finished"
这里通过write函数向python客户端传输字符串“1000001”,传输完毕后再在控制台打印finished
4)定义python客户端
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 14:45:20 2017
@author: linxiaojie
"""
from socket import *
host = "127.0.0.1"
port = 30000
client = socket(AF_INET, SOCK_STREAM)
client.connect((host, port))
client.send("hi,server!!")
response = client.recv(4096)
print response;
# client.close()
我采用的是python2.7,运行python程序后,plant就会接收到消息
再运行向python发送信息的方法后
python就会接收到消息(注:python客户端在接收一次plant传输的数据就会关闭,若要持续接收请自行拓展python代码)。
(2)plant作为客户端
1)plant作为客户端时,必须作为服务器的python运行后,这里的“开”才能点选,且必须“开”被点选了才能与python进行通讯。
2)定义回调方法self.Callback
param channelNo: integer, message: string
print to_str(message)
我这里仅打印python传输回来的数据。
3)定义数据传输方法
var str:string:=to_str(round(z_uniform(1,0,100),1))
socket2.write(0,str)
我这里是取随机数然后传输到python服务器。
4)定义python服务器
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 14:45:04 2017
@author: linxiaojie
"""
from socket import *
import threading
bind_ip = "127.0.0.1"
bind_port = 40000
server = socket(AF_INET, SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
# 定义一个服务端处理接口,初步支持并发接收client的请求
def handle_client(client_socket):
request = client_socket.recv(1024)
print request
client_socket.send("hi,client,")
while True:
client, addr = server.accept()
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
同样是python2.7的代码。
再运行plant的数据传输方法后
python端接收的数据:
plant回调方法接收的数据:
总结:
这篇文章只是简单介绍了plant与python通讯的一些方法与需要注意的点,初步实现了两端数据的流通,为需要用到这块的朋友提供一些帮助,后续各位可以根据需求做进一步的开发。
注:由于本人较忙,且没有对这块内容的需求,所以我对这块内容的了解也不是很深入,大家尽量自己学习,多查help,有问题可以留言,看到后会回复;若需要本人亲自指导,需要收取一定的辛苦费。