WSAStartup(2,WSAData);
Sock:=Socket(AF_INET,SOCK_STREAM,IPPROTO_IP);
SockAddrIn.sin_addr.S_addr:=inet_addr(PChar(ServerIP));
SockAddrIn.sin_Port:=htons(StrToInt(ServerPort));
SockAddrIn.sin_Family:=AF_INET;
SetSockOpt(Sock, SOL_SOCKET, SO_RCVBUF, Pchar(@buffer), 255);
Ret:=Connect(Sock,SockAddrIn,SizeOf(SockAddrIn));
WSAAsyncSelect(Sock,Handle,WM_SOCKET,FD_WRITE Or FD_CONNECT Or FD_CLOSE Or FD_READ);
这是连接的代码,然后交由 WM_SOCKET消息处理
procedure TForm_Main.OnSocket(Var Msg:TMessage);
Var
Ret:Integer;
Rep:TMtRepPacket;
sInfo,DialCode,sUserPhone,CurrentTimeStr:String;
Begin
CurrentTimeStr:=FormatDateTime('hh:nn:ss> ',Now);
If Msg.LParamLo=FD_CONNECT Then
MemInfo.Lines.Add(CurrentTimeStr+'连接SmGateway成功');
If Msg.LParamLo=FD_READ Then
Begin
If bIsHead Then
Begin
bIsHead:=False;
ZeroMemory(@rAceHead,SizeOf(TAceHead));
Ret:=recv(Msg.WParam,rAceHead,SizeOf(TAceHead),0);
End
Else
Begin
ZeroMemory(@Rep,SizeOf(TMtRepPacket));
bIsHead:=True;
Ret:=Recv(Msg.WParam,Rep,rAceHead.wMsgLen,0);
If Ret>SizeOf(TMsgHead) Then
Begin
Case Rep.rMsgHead.iCmdID Of
SMG_RegisterRep:
Begin
sInfo:='接收到注册返回信息(注册代码:'+Rep.rSmgRegisterRep.sServiceNumber+',注册结果:'+IntToStr(Rep.rSmgRegisterRep.byResult)+')';
MemInfo.Lines.Add(CurrentTimeStr+sInfo);
End;
SMG_UnRegisterRep:
Begin
sInfo:='接收到注销返回信息(注销代码:'+Rep.rSmgUnRegisterRep.sServiceNumber+',注销结果:'+IntToStr(Rep.rSmgUnRegisterRep.byResult)+')';
MemInfo.Lines.Add(CurrentTimeStr+sInfo);
End;
SMG_SubmitRep:
Begin
sInfo:='接收到下行返回信息(客户端序列号:'+IntToStr(Rep.rSmgSubmitRep.iClientSeqId)+'下发结果:'+IntToStr(rep.rSmgSubmitRep.byResult)+')';
//MemInfo.Lines.Add(CurrentTimeStr+sInfo);
End;
SMG_DeliverReq:
Begin
//将消息写入队列
EnQueue(Rep.rSmgDeliverReq, IndealQueueRec);
End;
End;
End;
End;
End;
If Msg.LParamLo=FD_CLOSE Then
Begin
MemInfo.Lines.Add(CurrentTimeStr+'与短信网关的连接被中断');
WSAAsyncSelect(Sock,Form_Main.Handle,WM_SOCKET,0);
CloseSocket(Sock);WSACleanup;
ConnectServerFlag:=True;
End;
End;