一、halcon自身封装了socket服务端和客户端的算子,可以直接调用实现TCP通讯。
二、案例
2.1 服务端代码
Protocol := ‘TCP4’
Timeout := 10
*
- 创建一个监听,设置端口为4660,超时为10s
open_socket_accept (4660, [‘protocol’,‘timeout’], [Protocol,Timeout], AcceptingSocket) - Strip AddressFamily from Protocl
tuple_regexp_match (Protocol, ‘TCP|HALCON’, BaseProtocol)
if (BaseProtocol == ‘TCP’ or BaseProtocol == ‘HALCON’)- Wait for an incoming connection, use the timeout of the
- AcceptingSocket
dev_error_var (Error, 1)
dev_set_check (‘~give_error’)
OpenStatus := 5
while (OpenStatus != 2)
socket_accept_connect (AcceptingSocket, ‘auto’, Socket)
OpenStatus := Error
endwhile
dev_set_check (‘give_error’) - Set the same timeout on the newly created socket
set_socket_param (Socket, ‘timeout’, Timeout)
else - UDP sockets do not need an accept()
Socket := AcceptingSocket
endif
get_socket_param (Socket, ‘address_info’, Address)
Answer := []
while (Answer != ‘End’)
receive_data (Socket, ‘z’, Answer, From)
To:=[]
Data:='received '+Answer
Format := ‘z’
send_data (Socket, Format, Data, To)
endwhile
stop ()
close_socket (Socket)
close_socket (AcceptingSocket)
2.2 客户端代码
- 创建一个客户端,设置ip为127.0.0.1,设置端口为1111,超时为10s
Ip := ‘127.0.0.1’
Port:=1111
Timeout := 10
Protocol := ‘TCP4’
open_socket_connect (‘127.0.0.1’, 1111, [‘protocol’,‘timeout’], [Protocol,Timeout], Socket) - Strip AddressFamily from Protocl
tuple_regexp_match (Protocol, ‘TCP|HALCON’, BaseProtocol)
if (BaseProtocol == ‘TCP’ or BaseProtocol == ‘HALCON’)- Wait for an incoming connection, use the timeout of the
- AcceptingSocket
- Set the same timeout on the newly created socket
set_socket_param (Socket, ‘timeout’, Timeout)
else - UDP sockets do not need an accept()
*Socket := AcceptingSocket
endif
get_socket_param (Socket, ‘address_info’, Address)
Answer := []
while (Answer != ‘End’)
receive_data (Socket, ‘z’, Answer, From)
To:=[]
Data:='received '+Answer
Format := ‘z’
send_data (Socket, Format, Data, To)
endwhile
stop ()
close_socket (Socket)