我正在使用 TF6310 TCP/IP 启动 TCP 服务器,等待连接(保证只有一个客户端连接),当连接到来时我接受它。一旦被接受,我就会接收/发送数据。
我遇到的问题是我无法识别客户端是否断开连接,并且我无法弄清楚如何检测到它以关闭套接字。
特别是,只要客户端连接,我只想留在第 3 步,如果他断开连接,我想转到第 100 步。
1: // Open Listener-Socket
fbSocketListen(
sSrvNetId:='',
sLocalHost:=sLocalHost,
nLocalPort:=nLocalPort,
bExecute:=TRUE,
tTimeout:=T#5S,
bBusy=> ,
bError=>bError,
nErrId=>nErrorID,
hListener=>hListener);
IF hListener.handle <> 0
THEN
iState:=2;
ELSIF bError
THEN
iState:=99;
END_IF
2: // Accept Client connection
fbSocketAccept(
sSrvNetId:='',
hListener:=fbSocketListen.hListener,
bExecute:= bAcceptExecute:= NOT bAcceptExecute,
tTimeout:=T#5S,
bAccepted=> ,
bBusy=> ,
bError=>bError,
nErrId=>nErrorID,
hSocket=>hSocket);
// bExecute:= bAcceptExecute:= NOT bAcceptExecute,
IF bError
THEN
iState:=99;
ELSIF hSocket.handle <> 0
THEN
iState:=3;
bConnected:=TRUE;
END_IF
3: // client connected, send and receive data
fbSocketListen();
fbSocketAccept();
fbSocketReceive(
sSrvNetId:='',
hSocket:=fbSocketAccept.hSocket,
cbLen:=SIZEOF(stDataRx),
pDest:=ADR(stDataRx),
bExecute:= bReceiveExecute:= NOT bReceiveExecute, // Check for new client telegrams every second cycle
tTimeout:=T#14S,
bBusy=> ,
bError=>bError,
nErrId=>nErrorID,
nRecBytes=> );
IF fbSocketReceive.nRecBytes <> 0 // Switch to send-state when data are received
THEN
bNewDataReceived:=TRUE;
END_IF
IF fbSocketReceive.bError OR(NOT bEnable) // Close connection when error is occuring or trigger is set
THEN
iState:=100;
END_IF
IF bNewDataReceived THEN
(* got data, write it to the outputs.. *)
stScannerRx := stDataRx;
bNewDataReceived := FALSE;
END_IF
impNewPal(clk:=bNewPal);
IF impNewPal.Q THEN
MEMSET(ADR(stScannerRx),16#00,SIZEOF(stScannerRx));
END_IF
(* if a new crate is ready, send the packet *)
IF bNewPal THEN
stDataTx.iPalId := iPalId;
stDataTx.iStackId := iStackId;
stDataTx.bReady := 1;
stDataTx.iCrateCnt := iCrateCnt;
fbSocketSend( // Send Data to client
sSrvNetId:='',
hSocket:=hSocket,
cbLen:=SIZEOF(stDataTx),
pSrc:=ADR(stDataTx),
bExecute:=TRUE,
tTimeout:=T#3S,
bBusy=> ,
bError=>bError,
nErrId=>nErrorID);
ELSE
fbSocketSend(bExecute:=FALSE);
END_IF
IF fbSocketSend.bError
THEN
iState:=100; // Close connection in case of error
END_IF