下面这种方式的方式做tcp连接,怎么做一个多线程的 (100分)

  • 主题发起人 主题发起人 盛利
  • 开始时间 开始时间

盛利

Unregistered / Unconfirmed
GUEST, unregistred user!
比如我要开10个线程
创建10个socket,但是消息确是一个,怎么办
WSAAsyncSelect(s, Form1.Handle, WM_CLIENT_READCLOSE, FD_CLOSE xor FD_READ);
这句不好办啊,或者多线程是用的别的方法????

控件的方法不要,请不要贴


const
WM_CLIENT_READ = WM_USER + 103; //自定义windows消息
WM_CLIENT_READCLOSE = WM_USER + 105;
WM_BARICON = WM_USER + 200;

// 初始化SOCKET dll
if WSAStartup($101, TempWSAData) = 1 then
showmessage('WSAStartup Error!');
s := Socket(AF_INET, SOCK_STREAM, 0); //tcp通讯
//Socket创建失败
if (s = INVALID_SOCKET) then
begin
showmessage(inttostr(WSAGetLastError()) + ' Socket创建失败');
CloseSocket(s); exit;
end;
//判断ip地址的格式
ulHostAddress := inet_addr(pchar(serverip));
if (ulHostAddress < 0) then
begin
ulHostAddress := GetHostAddress(serverip);
in_.S_addr := ulHostAddress;
end;
//发送方SockAddr绑定
addr.sin_family := AF_INET;
addr.sin_addr.S_addr := ulHostAddress;
addr.sin_port := htons(port);
if connect(s, addr, sizeof(addr)) <> 0 then
begin
memo1.Lines.Add('connect fail');
end
else
memo1.Lines.Add('connected');
WSAAsyncSelect(s, Form1.Handle, WM_CLIENT_READCLOSE, FD_CLOSE xor FD_READ);
 
用完成端口,或者重叠i/o,
最简单的方式是用诸塞模式+多线程
 
你是做扫描工具把?不要用WSAAsyncSelect,直接用select来做,很简单,
 
不知道有没有select和WSAAsyncSelect的区别或者说明

:张无忌能讲解一下吗??

或者不用控件,还有其他的方法或者例子什么的,多线程下载

int select (
int nfds,
fd_set FAR * readfds,
fd_set FAR * writefds,
fd_set FAR * exceptfds,
const struct timeval FAR * timeout
);
 
select的使用你可以看DELPI的TServerSocket和TClientSocket的代码,
哪个TSockStream什么的,有个WaitForData就是用这个函数的,
 
张无忌:方便给我写个例子可以吗?
谢谢!
 
10线程:
program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils, WinSock, Windows;

var
WSAData: TWSAData;
Ret: Integer;
s: TSocket;
i: Integer;
ThreadID: Cardinal;

procedure WorkThread(Param: Pointer); stdcall;
var
s: TSocket;
ServerAddr: TSockAddrIn;
begin
s:=TSocket(Param);

ServerAddr.sin_family:=AF_INET;
ServerAddr.sin_port:=21; //replace your port
ServerAddr.sin_addr.S_addr:=inet_addr('127.0.0.1'); //replace your server IP
if connect(s, ServerAddr, SizeOf(ServerAddr))=SOCKET_ERROR then
begin
//Handle the error WSAGetLastError
end;
//DoSomeThing with s;
CloseSocket(s)
end;

begin
Ret:=WSAStartup($101, WSAData);
if Ret<>0 then
begin
WriteLn('WSAStartup failed with error', Ret);
Exit
end;

for i:=1 to 10 do
begin
s:=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if s=INVALID_SOCKET then
begin
WriteLn('socket failed with error', WSAGetLastError);
Break
end;
CreateThread(nil, 0, @WorkThread, Pointer(s), 0, ThreadID)
end;

ReadLn;

WSACleanup
end.
 
后退
顶部