{type
sockaddr_in = record
case integer of
0: (sin_family: u_short;
sin_port: u_short;
sin_addr: tinaddr;
sin_zero: array[0..7] of char);
1: (sa_family: u_short;
sa_data: array[0..13] of char)
end;
tsockaddrin = sockaddr_in;
psockaddr = ^tsockaddr;
tsockaddr = sockaddr_in;
wsadata = record // !!! also wsdata
wversion: word;
whighversion: word;
szdescription: array[0..wsadescription_len] of char;
szsystemstatus: array[0..wsasys_status_len] of char;
imaxsockets: word;
imaxudpdg: word;
lpvendorinfo: pchar;
end;
twsadata = wsadata;
end
}
var str:string;
s,ns:tsocket;//type:u_int|integer;
ver:word;
rece:twsadata;//type:wsadata;
wsstatus:integer;//winsocket_status;
i,pktlen:integer;
szd:array[0..wsadescription_len] of char;
szs:array[0..wsasys_status_len] of char;
server:tsockaddr;//tpye:sockaddr_in
client:psockaddr;//type:^sockaddr_in
namelen:pinteger;//type:^integer;
buf:array[0..1023] of char;
begin
ver:=514;
write('wsastartup = ');
try
wsstatus:=wsastartup(ver,rece);
//初始化winsock;在windows下是必须的过程
writeln(wsstatus);//winsock状态,0代表成功
if wsstatus=0 then
begin
writeln;
writeln('********************************************************************************');
//以下显示winsock状态
write('wversion = ');
writeln(rece.wversion);
write('whighversion = ');
writeln(rece.whighversion);
write('imaxsockets = ');
writeln(rece.imaxsockets);
write('imaxudpdg = ');
writeln(rece.imaxudpdg);
writeln('szdescription is ');
for i:=0 to wsadescription_len do write(szd[i]);
writeln;
writeln('szsystemstatus is ');
for i:=0 to wsasys_status_len do write(szs[i]);
writeln;
writeln('********************************************************************************');
end;
write('socket = ');
s:=socket(af_inet,sock_stream,0);
//第一步,建立服务器的socket,0表示成功
writeln(s);
if s<0 then exit;
write('bind = ');
server.sin_family := af_inet;
server.sin_port := htons(myport);
server.sin_addr.s_addr := inaddr_any;
wsstatus:=bind(s,server,sizeof(server));
//第二步,绑定,0表示成功
writeln(wsstatus);
if wsstatus<>0 then exit;
write('listen = ');
wsstatus:=listen(s,5);
//第三步,监听
writeln(wsstatus);
if wsstatus<>0 then exit;
write('accept = ');
new(client);
new(namelen);
namelen^:=sizeof(client^);
ns:=accept(s,client,namelen);
//第四步,等待接收
//注:bind时传递的是sockaddr_in结构的数据,accept时是两个指针!!!
if ns=-1 then //以下可以做成多线程过程
begin
writeln(-1);
exit;
end
else
begin
writeln(ns);
pktlen:=0;
writeln('recv');
repeat
pktlen:= recv(ns,buf,1024,0);//接收数据
//pktlen=为接收长度,0表示断开联接,<0表示失败
sleep(1);
write(pktlen:5);
if pktlen>0 then
begin
i:=send(ns,buf,pktlen,0);//返回数据
end;
until pktlen<1;//循环直到客户断开联接
end;
finally
writeln;
writeln('********************************************************************************');
writeln('press to exit winsocket');
readln(str);
wsstatus:=wsacleanup();//退出winsocket;
write('wsacleanup = ');
writeln(wsstatus);
end;
writeln;
writeln('press to exit');
readln(str);
end.