扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
procedure TListenThread.Execute; var addr : TSockAddrIn; fd_read : TFDSet; timeout : TTimeVal; ASock, MainSock : TSocket; len, i : Integer; begin MainSock := socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); addr.sin_family := AF_INET; addr.sin_port := htons(5678); addr.sin_addr.S_addr := htonl(INADDR_ANY); bind( MainSock, @addr, sizeof(addr) ); listen( MainSock, 5 ); while (not Terminated) do begin FD_ZERO( fd_read ); FD_SET( MainSock, fd_read ); timeout.tv_sec := 0; timeout.tv_usec := 500; if select( 0, @fd_read, nil, nil, @timeout ) > 0 then //至少有1个等待Accept的connection begin if FD_ISSET( MainSock, fd_read ) then begin for i:=0 to fd_read.fd_count-1 do //注意,fd_count <= 64,也就是说select只能同时管理最多64个连接 begin len := sizeof(addr); ASock := accept( MainSock, addr, len ); if ASock <> INVALID_SOCKET then ....//为ASock创建一个新的线程,在新的线程中再不停地select end; end; end; end; //while (not self.Terminated) shutdown( MainSock, SD_BOTH ); closesocket( MainSock ); end; |
const WM_SOCKET = WM_USER + 55; |
private procedure WMSocket(var Msg: TMessage); message WM_SOCKET; |
var addr : TSockAddr; sock : TSocket; sock := socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); addr.sin_family := AF_INET; addr.sin_port := htons(5678); addr.sin_addr.S_addr := htonl(INADDR_ANY); bind( m_sock, @addr, sizeof(SOCKADDR) ); WSAAsyncSelect( m_sock, Handle, WM_SOCKET, FD_ACCEPT or FD_CLOSE ); listen( m_sock, 5 ); .... |
procedure TfmMain.WMSocket(var Msg: TMessage); var sock : TSocket; addr : TSockAddrIn; addrlen : Integer; buf : Array [0..4095] of Char; begin //Msg的WParam是产生了网络事件的socket句柄,LParam则包含了事件类型 case WSAGetSelectEvent( Msg.LParam ) of FD_ACCEPT : begin addrlen := sizeof(addr); sock := accept( Msg.WParam, addr, addrlen ); if sock <> INVALID_SOCKET then WSAAsyncSelect( sock, Handle, WM_SOCKET, FD_READ or FD_WRITE or FD_CLOSE ); end; FD_CLOSE : closesocket( Msg.WParam ); FD_READ : recv( Msg.WParam, buf[0], 4096, 0 ); FD_WRITE : ; end; end; |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者