精简了一下,可能有错的<br>unit Unit1;<br><br>interface<br><br>uses<br> Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,<br> Dialogs;<br><br>type<br> TForm1 = class(TForm)<br> private<br> { Private declarations }<br> public<br> { Public declarations }<br> end;<br> TWinSockThread=class(TThread)<br> private<br> CliAddrIn:TSockAddrIn; //winsock地址结构(监测系统IP地址、端口)<br> procedure OnTimer; //定时器事件<br> procedure OnSocket(Event:Word); //WinSock事件<br> procedure WndProc(var Message: TMessage); //窗体过程<br> procedure SockConnect; //连接<br> protected<br> procedure Execute;override;<br> public<br> TimerID:Integer; //定时器编号<br> WinSockThreadHandle:HWnd; //隐含窗体句柄<br> Connected:Boolean; //是否连接<br> CliSocket:Integer; //WinsockID<br>end;<br><br>var<br> Form1: TForm1;<br><br>implementation<br><br>{$R *.dfm}<br>procedure TWinSockThread.Execute;<br>var<br> Msg:TMsg;<br>begin<br> FreeOnTerminate:=True;<br> WinSockThreadHandle:=Classes.AllocateHWnd(WndProc);<br> WSAStartup(MAKEWORD(2,2),WSAData);<br> Connected:=True;<br> SockConnect;<br> TimerID:=SetTimer(WinSockThreadHandle,0,3000,nil);<br> while GetMessage(Msg,WinSockThreadHandle,0,0) do<br> DispatchMessage(Msg);<br> KillTimer(WinSockThreadHandle,TimerID);<br> CloseSocket(CliSocket);<br> WSACleanUP();<br> Classes.DeallocateHWnd(WinSockThreadHandle);<br>end;<br><br>procedure TWinSockThread.OnSocket(Event:Word);<br>var<br> Buf:array[0..1023] of Byte;<br><br>begin<br> KillTimer(WinSockThreadHandle,TimerID);<br> case Event of<br> FD_READ: //读取数据<br> begin<br> //操作<br> end;<br> end;<br>end;<br><br><br>procedure TWinSockThread.SockConnect; //连接<br>var<br> err:Integer;<br>begin<br> CliSocket := socket(AF_INET, SOCK_STREAM,IPPROTO_IP);<br> if (CliSocket = INVALID_SOCKET) then<br> begin<br> CloseSocket(CliSocket);<br> Exit;<br> end;<br> ZeroMemory(@CliAddrIn,sizeof(CliAddrIn));<br> CliAddrIn.sin_addr.s_addr:=Inet_Addr(PChar(SockIP));<br> CliAddrIn.sin_family := AF_INET;<br> CliAddrIn.sin_port :=Htons(SockPort);<br> err:=Connect(CliSocket,CliAddrIn, SizeOf(CliAddrIn));<br> if err = 0 then<br> begin<br> Connected:=True;<br>// Shape.Brush.Color:=clLime;<br> end<br> else<br> begin<br> //Form1.ListBox2.Items.Add(IntToStr(WSAGetLastError()));<br> // Connected:=False;<br> end; //绑定消息映射<br> WSAAsyncSelect(CliSocket,WinSockThreadHandle, WM_SOCK, FD_READ or FD_Accept or FD_CONNECT or FD_WRITE or FD_CLOSE);<br>end;<br><br>procedure TWinSockThread.OnTimer;//定时器事件<br>var<br> errclose:integer;<br>begin<br> errclose:=CloseSocket(CliSocket);<br>end;<br><br>procedure TWinSockThread.WndProc(var Message: TMessage); //隐含窗体过程<br>begin<br> case Message.Msg of<br> WM_Timer:<br> begin<br> OnTimer; //响应定时器事件<br> end;<br> WM_Sock:<br> begin<br> OnSocket(WSAGetSelectEvent(Message.LParam)); //响应WinSock事件<br> end;<br> end;<br>end;<br><br>end.<br>