Сообщение было отмечено SkiHunter как решение
Решение
Сервер
Delphi | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
| unit Server;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
WinSock, StdCtrls, ExtCtrls;
type
TMyThread = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;
TForm1 = class(TForm)
Listen1: TButton;
Stop1: TButton;
procedure Listen1Click(Sender: TObject);
procedure Stop1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
var Sockets:array of TSocket;
Addr:TSockAddr;
Data:TWSAData;
I,J:Integer;
FDSet:TFDSet;
buf,buf1: string;
Timeout: TTimeVal;
My_thread: TMyThread;
listen_socket:TSocket;
Len:integer;
{$R *.dfm}
procedure TMyThread.Execute;
begin
while true do
begin
// обнуляем Множество
FD_ZERO(FDSet);
// заносим в множество прослушивающий сокет
FD_SET(Listen_socket,FDSet);
// пробегаемся по всем сокетам, загоняем все работаю-
// щие сокеты в множество
for i:=Low(Sockets) to High(Sockets) do
if Sockets[i]<>INVALID_SOCKET then
FD_SET(Sockets[i],FDSet);
// Функция Select возвращает общее количество сокетов,
// находящихся в состоянии готовности. Если оно равно нулю,
// значит нет сокетов в состоянии готовности.
if select(0,@FDSet,nil,nil,@TimeOut)=0 then Continue;
// Если есть сокеты в состоянии готовности, то
if FD_ISSET(Listen_socket,FDSet) then
begin
i:=Low(Sockets);
// проверяем массив на наличие сокетов, вышедших из строя
while i<=High(Sockets) do
begin
if Sockets[i]=INVALID_SOCKET then
break;
inc(i);
end;
// добавляем новый обслуживающий сокет
if i>High(Sockets) then SetLength(Sockets,i+1);
j:=SizeOf(TSockAddr);
Sockets[i]:=Accept(listen_socket,@Addr,@j);
end;
// получаем данные от клиента/клиентов
for i:=Low(Sockets) to High(Sockets) do
begin
if FD_ISSET(Sockets[i],FDSet) then
begin
SetLength(buf,4096);
SetLength(buf,recv(Sockets[i],buf[1],Length(buf),0));
// если буфер пуст, то клиент закрыл соединение.
// нужно удалить сокет из массива.
if length(buf)= 0 then
begin
CloseHandle(Sockets[i]);
Sockets[i]:=INVALID_SOCKET;
FD_clr(Sockets[i],FDSet);
end else
// иначе отправить данные всем
for j := 0 to high(sockets) do
send(sockets[j],buf[1],length(buf),0);
end;
end;
end;
end;
procedure TForm1.Listen1Click(Sender: TObject);
begin
WSAStartup($101,Data);
listen_socket:=Socket(AF_INET,SOCK_STREAM,IPPROTO_IP);
Addr.sin_family:=AF_INET;
Addr.sin_port:=HToNS(25);
Addr.sin_addr.S_addr:=InAddr_Any;
FillChar(Addr.Sin_Zero,SizeOf(Addr.Sin_Zero),0);
If Bind(listen_socket,Addr,SizeOf(TSockAddr))<>0 then exit;
If Listen(listen_socket,SoMaxConn)<>0 then exit;
TimeOut.tv_sec:=2;
TimeOut.tv_usec:=0;
Listen1.Enabled:=False;
Stop1.Enabled:=True;
My_Thread:=TMyThread.Create(true);
with My_Thread do
Begin
Priority := tpLower;
Resume;
end;
end;
procedure TForm1.Stop1Click(Sender: TObject);
begin
I:=0;
My_Thread.Suspend;
FD_ZERO(FDSet);
For I:= High(Sockets) downto 0 do
begin
CloseSocket(Sockets[I]);
end;
i:=0;
closeSocket(listen_socket);
setLength(sockets,i);
Stop1.Enabled:=False;
Listen1.Enabled:=True;
My_Thread.Terminate;
end;
end. |
|
Клиент
Delphi | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
| unit client;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
WinSock, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Timer1: TTimer;
Button2: TButton;
Button3: TButton;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
// procedure Timer1Timer(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
My_thread=class(TTHread)
private
procedure Execute; override;
end;
var
Form1: TForm1;
implementation
var
conn: boolean;
S:TSocket;
Addr:TSockAddr;
Data:TWSAData;
i,j:integer;
sending,receiver:String;
H:My_Thread;
var
FDSet:TFDSet;
TimeOut:TTimeVal;
{$R *.dfm}
procedure My_Thread.Execute;
begin
while True do
begin
FD_zero(FDSet);
FD_Set(s,FDSet);
TimeOut.tv_sec:=2;
if select(0,@FDSet,nil,nil,@TimeOut)<>0 then
begin
setlength(sending,4096);
setlength(sending,recv(s,sending[1],length(sending),0));
Form1.memo1.Lines.Add(sending);
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if not conn then
begin
WSAStartup($101,Data);
S:=Socket(AF_Inet,Sock_Stream,IPPROTO_IP);
Addr.sin_family:=AF_Inet;
Addr.sin_port:=HToNS(25);
Addr.sin_addr.S_addr:=Inet_Addr('127.0.0.1');
FillChar(Addr.Sin_Zero,SizeOf(Addr.Sin_Zero),0);
If Connect(S,Addr,SizeOf(TSockAddr))=0 then
begin
conn:=true;
Memo1.lines.Add('Connect ok');
H:=My_Thread.Create(true);
with H do
Begin
Priority := tpLower;
Resume;
end;
end
else showmessage(inttostr(WsaGetLastError));
end
else ShowMessage('connected yet');
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
H.Suspend;
CloseSocket(S);
conn:=false;
memo1.Clear;
H.Terminate;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
sending:='клиент '+form1.Caption[length(form1.Caption)]+':'+Edit1.Text;
send(s,sending[1],length(sending),0);
end;
procedure TForm1.FormActivate(Sender: TObject);
begin
Conn:=false;
Randomize;
end;
procedure TForm1.FormCreate(Sender: TObject);
var hwnd: THandle;
begin
i:=0;
repeat
inc(i);
hwnd := FindWindow('TForm1', PAnsiChar('Client'+' '+inttostr(i)));
until hwnd=0;
Form1.Caption:= Form1.Caption+' '+inttostr(i);
end;
{procedure TForm1.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled:=False;
timer1.Interval:=1000*Trunc(Random(1200));
Button1Click(sender);
timer1.Enabled:=true;
end;
}
end. |
|
Добавлено через 5 минут
Отправка всем клиентам сразу
Delphi | 1
2
| for j := 0 to high(sockets) do
send(sockets[j],buf[1],length(buf),0); |
|
2
|