Halcon uses Socket to realize TCP communication

1. Halcon itself encapsulates the socket server and client operators, which can be directly called to implement TCP communication.
2. Case
2.1 Server code

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 Client code

*
* 创建一个客户端,设置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)

Guess you like

Origin blog.csdn.net/Douhaoyu/article/details/128319110