6
6713827
Unregistered / Unconfirmed
GUEST, unregistred user!
const<br> WM_SOCKET = WM_USER + $1000;<br>type <br>TNet=class<br>private<br> {SOCKET消息钩子}<br> procedure SockProssMsg(var Msg : TMessage); Message WM_SOCKET;<br>public<br> {初始化SOCKET}<br> function SocketInitialize: Boolean;<br> {关闭SOCKET}<br> function SocketFinalize: Boolean;<br> {SOCKET连接}<br> function SocketConnect: Boolean;<br> {SOCKET消息发送}<br> function SocketSend(S:String): Boolean;<br>end;<br>function TNet.SocketInitialize: Boolean;<br>begin<br>Result:=True;<br>try<br>if not InitializeSocket then begin<br>writeln('初始化Socket错误'+' 错误代码为: '+IntToStr(WSAGetLastError()));<br>end Else<br>Begin<br>writeln('初始化Socket成功');<br>SocketIni:=True;<br>end;<br>except<br>Result:=False;<br>end;<br>end;<br><br>function TNet.SocketFinalize: Boolean;<br>begin<br>Result:=True;<br>try<br>if not cleanupSocket then begin<br> writeln('关闭Socket错误'+' 错误代码为: '+ IntToStr(WSAGetLastError()));<br>end Else<br>Begin<br>writeln('关闭Socket成功');<br>SocketIni:=True;<br>SocketConn:=True;<br>end;<br>except<br>Result:=False;<br>end;<br>end;<br><br>function TNet.SocketConnect: Boolean;<br>begin<br>Result:=True;<br>try<br>CliSock:= Socket(AF_INET,Sock_Stream,IPPROTO_TCP);<br>if Not SocketIni then SocketInitialize;<br>{初始化连接}<br>if CliSock = INVALID_SOCKET then begin<br> writeln('初始化Sock套接字失败'+ ' 错误代码为:'+ IntToStr(WSAGetLastError()));<br> CloseSocket(Clisock);<br>end Else writeln('初始化Sock套接字成功');<br>{开始连接}<br>if not ConnectIP(CliSock,Ip,Port) then begin<br> writeln('连接服务器错误.'+'错误代码: '+ IntToStr(WSAGetLastError()));<br>end<br>else begin<br> WSAAsyncSelect(CliSock,Handle,WM_SOCKET,FD_READ or FD_CLOSE Or SOCKET_ERROR Or FD_WRITE Or FD_CONNECT);<br> SocketConn:=True;<br> writeln('连接到服务器成功');<br> SocketSend('收到次消息表示连接成功');<br>end;<br>except<br>Result:=False;<br>end;<br>end;<br><br>procedure TNet.SockProssMsg(var Msg: TMessage);<br>Var<br> RecvMsg: Integer;<br> RecvLen: longint;<br> RecvData: Buff;<br> RecvStr: string;<br>Begin<br> writeln('消息处理事件'); <br> RecvMsg:= WSAGetSelectError(Msg.LParam);<br> case RecvMsg of<br> SOCKET_ERROR:writeln('连接错误');<br> FD_CLOSE:writeln('与服务器断开连接');<br> FD_READ:<br> Begin<br> writeln('接收数据错误');<br> RecvLen:= Recv(Msg.WParam,RecvData,Sizeof(Recvdata),0);<br> if RecvLen = SOCKET_ERROR then<br> begin<br> writeln('接收数据错误!');<br> end<br> Else<br> Begin<br> RecvStr:= Trim(Copy(RecvData,0,Length(RecvData)));<br> writeln(RecvStr);<br> end;<br> end;<br> end; <br>end;<br><br>function TNet.SocketSend(S:String): Boolean;<br>Begin<br>Result:=True;<br>Try<br> writeln('开始发送消息!');<br> if Send(CliSock,Pointer(pchar(s))^,length(s),0) = SOCKET_ERROR then begin<br> writeln('发送消息到服务器错误!请重试!!');<br> CloseSocket(CliSock);<br> Result:=False;<br> end Else writeln('消息发送成功!');<br>except<br>Result:=False;<br>end;<br>end;<br><br>程序部分代码!<br>运行情况:<br>程序运行时,SOCKET没问题,消息能正确发送,服务端能正确接受;<br>问题:<br>当服务器向客户端发送消息时,客户端没有触发消息事件(SockProssMsg);<br>报告完毕。<br>请大侠指点!