1. Halcon 자체는 TCP 통신을 구현하기 위해 직접 호출할 수 있는 소켓 서버 및 클라이언트 연산자를 캡슐화합니다.
2. 사례
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)