sleep被否定了,呵呵,那就来个分包读取吧 ^_^
所有关系到收发数据的缓冲区都属于简单的char类型,即面向字节的数据。
{接收端}
const
BackLog = 5;
var
wsaData: TWSAData;
ServerAddr: TSockAddrIn;
ClientAddr: PSockAddr;
AddrLen: PInteger;
buf: TBuf;
nLeft, idx, ret: integer;
begin
FreeOnTerminate := true;
WSAStartup(MakeWord(2,2), wsaData);
ListenSock := socket(AF_INET, Sock_Stream, IPProto_TCP);
ServerAddr.sin_family := AF_INET;
ServerAddr.sin_port := htons(port);
ServerAddr.sin_addr.S_addr := htonl(INADDR_ANY);
bind(ListenSock, ServerAddr, SizeOf(ServerAddr));
listen(ListenSock, BackLog);
new(ClientAddr);
new(AddrLen);
ClientSock := accept(ListenSock, ClientAddr, AddrLen);
if ClientSock = socket_error then
raise exception.Create(IntToStr(wsaGetLastError));
while not self.Terminated do
begin
nLeft := BufSize;
idx := 0;
while nLeft > 0 do //如果nLeft=0,说明已完整地读取了一个数据包
begin
ret := recv(ClientSock, buf[idx], nLeft, 0);
if ret = socket_error then continue;
dec(nLeft, ret); //nLeft := 数据包长度 - 已读取的长度 = 未读取长度
inc(idx, ret); //已读取的长度,作为buf的开始
end;
FMsg := buf;
FMsg := FMsg + #13;
Synchronize(ShowMsg);
end;
dispose(AddrLen);
dispose(ClientAddr);
CloseSocket(ClientSock);
CloseSocket(ListenSock);
WSACleanup;
end;
*************************************************************************************
{发送端}
const
IP = '192.168.1.6';
var
wsaData: TWSAData;
ServerAddr: TSockAddrIn;
buf: TBuf;
nLeft, idx, i, ret: integer;
str: string;
begin
FreeOnTerminate := true;
WSAStartup(MakeWord(2,2), wsaData);
s := socket(AF_INET, sock_stream, IPProto_TCP);
ServerAddr.sin_family := af_inet;
ServerAddr.sin_port := htons(port);
ServerAddr.sin_addr.S_addr := inet_addr(IP);
if connect(s, ServerAddr, SizeOf(ServerAddr)) = socket_error then
raise exception.Create(IntToStr(wsaGetLastError));
while not Self.Terminated do
begin
for i:=0 to 20 do
begin
str := IntToStr(i);
buf := StrToBuf(str);
nLeft := BufSize;
idx := 0;
while nLeft > 0 do
begin
ret := send(s, buf[idx], nLeft, 0);
if ret = socket_error then
begin
FMsg := '发送错误:' + buf;
Synchronize(ShowMsg);
end;
dec(nLeft, ret);
inc(idx, ret);
end;
end;
FMsg := '发送完毕.';
Synchronize(ShowMsg);
ret := recv(s, buf, BufSize, 0);
if ret = socket_error then
continue;
FMsg := '[收到字节数]' + IntToStr(ret);
Synchronize(ShowMsg);
FMsg := '[收到的内容]' + buf;
Synchronize(ShowMsg);
FMsg := '--------------------------';
Synchronize(ShowMsg);
end;
CloseSocket(s);
end;