*最近在TCP连接中遇到Halcon做服务器 无法运行的问题。卡在open_socket_accept这个算子。最终发现少了一个address。
算子参数解释为
The generic parameter ‘address’ can be used to instruct the socket to accept only connection requests addressed to a specific address. This address is specified as either an IPv4 or IPv6 address in numerical form, or a hostname. For example, ‘localhost’ would instruct the socket to accept only connections addressed to the address ‘localhost’, which normally maps to the local loopback network interface ‘127.0.0.1’.
通用参数“地址”可用于指示套接字仅接受寻址到特定地址的连接请求。该地址以数字形式指定为IPv4或IPv6地址,或者主机名。例如,“本地主机”将指示套接字只接受寻址到地址“本地主机”的连接,该地址通常映射到本地环回网络接口“127.0.0.1”。
因此加上服务器的本机地址就可以了。
open_socket_accept (4660, [‘address’,‘protocol’,‘timeout’], [address,Protocol,Timeout], AcceptingSocket)
* ***********************************************************************
*打开另一个例程generic_socket_send.hdev,先运行当前例程,再运行generic_socket_send.hdev
*当前例程是做服务器,generic_socket_send.hdev例程是做客户端.
*本书讲述 不使用generic_socket_send.hdev例程,打开TCP通讯助手软件,设置为客户端,服务器IP地址127.0.0.1 端口4660
*127.0.0.1是本机内部测试使用,与其他电脑或设备连接,需要修改地址
*************************************************************************
* Initialize program 初始化,协议TCP4 Timeout:超时时间 单位秒,36000秒=10小时
Protocol := 'TCP4'
Timeout := 36000
*与外部连接时的静态IP地址(本机),两个设备的IP地址前三位,如:192.168.125相同,第四位不同
* address:='192.168.125.12'
*本机内部连接时的ip地址
address:='127.0.0.1'
*
* Open a listening socket 打开端口4660 10小时内没有打开则返回失败
open_socket_accept (4660, ['address','protocol','timeout'], [address,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
*获取当前客户端IP地址和端口号
get_socket_param (Socket, 'address_info', Address)
*写一个循环来接受数据 发送数据
while(true)
Receive_date := []
*Date_received就是接收到的客户端所发送的数据,'z'是转码格式,转为字符串,保留即可。
receive_data (Socket, 'z', Receive_date, From)
Date_received := Receive_date
To := [From[0],From[1]]
Format := 'z'
stop()
*发送数据给客户端
Date_send:='I have received the message:'+Date_received
send_data (Socket, Format, Date_send, To)
endwhile
stop ()
*关闭通讯
close_socket (Socket)
close_socket (AcceptingSocket)