以下是关键处理代码,请帮看看
procedure TForm1.processsocketmsg(var msg : Tmessage);
procedure recordinfo(info : string);
begin
memo1.Lines.add(info);
end;
var
Client_Addr: TSockAddr;
ClientLen: Integer;
recv_buff : Tsock_info;
ret : integer;
i,j : integer;
xfdset : Tfdset;
xtimeval : TTimeVal;
begin
edit3.text := '';
for i := 0 to clients.Count - 1 do begin
fd_zero(xfdset);
fd_set(integer(clients),xfdset);
xtimeval.tv_sec := 0;
xtimeval.tv_usec := 50;
ret := select(0,@xfdset,nil,nil,@xtimeval);
client_socket := integer(clients);
if (ret>0) then begin
case wsagetselectevent(msg.LParam) of
fd_read : begin
ret := recv(client_socket,recv_buff,sizeof(recv_buff),0) ;
if ret=socket_error then begin
showmessage('read data error');
end else if ret>0 then begin
recordinfo(timetostr(recv_buff.time) + ' : ' + recv_buff.info);
end;
end;
fd_close : begin
closesocket(client_socket);
clients.Remove(pointer(client_socket));
{删除listbox1中对应的项}
for j := 0 to listbox1.count - 1 do begin
if pos(inttostr(client_socket),listbox1.Items[j])>0 then listbox1.Items.Delete(j);
end;
end;
end;
end;
end;
{如果accept,记录新SOCKET}
case wsagetselectevent(msg.LParam) of
fd_accept : begin
FillChar(Client_Addr,Sizeof(Client_Addr),0);
ClientLen := Sizeof(Client_Addr);
Client_Socket := Accept(sockserver,@Client_Addr,@ClientLen);
if client_socket <> invalid_socket then begin
listbox1.Items.Add(inttostr(Client_Socket) + ' : ' + inet_ntoa(client_addr.sin_addr));
clients.Add(pointer(Client_socket));
button2.Enabled := true;
button3.Enabled := true;
end;
setsockopt(client_socket,sol_socket,so_sndbuf,pointer(sock_buff),sizeof(integer));
setsockopt(client_socket,sol_socket,so_rcvbuf,pointer(sock_buff),sizeof(integer));
wsaasyncselect(Client_Socket,handle,wm_socket,fd_read or fd_close);
end;
end;
end;