码迷,mamicode.com
首页 > 其他好文 > 详细

socket 通信

时间:2016-01-14 00:55:35      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

   

type
TWinSocketStringStream = class(TWinSocketStream)
public
function ReadString(nMaxLength: Integer; var str, sErrMsg: string): Boolean;
function WriteString(const str: string; var sErrMsg: string): Boolean;
end;

对delphi中的类TWinSocketStream进行继承,封装socket传输信息以及提供直接输入字符串方式进行socket传输

unction TWinSocketStringStream.ReadString(nMaxLength: Integer;
var str, sErrMsg: string): Boolean;
var
Buffer: array[0..MAXDATALEN] of byte;
LenBuffer: array[0..10] of byte;
rcvLen, txLen, dataLen: Integer;
begin
Result := false;
str := ‘‘;
sErrMsg := ‘‘;
try
(*
第一个循环读str长度
*)
dataLen := -1;
txLen := 0;
while dataLen = -1 do
begin
rcvLen := sizeof(dataLen) - txLen;
rcvLen := Read(Buffer, rcvLen);
if rcvLen = 0 then
begin
sErrMsg := Format(‘只能读取字符串长度的%d/%d‘, [txLen, sizeof(dataLen)]);
Exit;
end;
Move(Buffer, LenBuffer[txLen], rcvLen);
Inc(txLen, rcvLen);
if txLen = sizeof(dataLen) then
begin
Move(LenBuffer, dataLen, sizeof(dataLen));
break;
end;
end;
nMaxLength := dataLen; //Dynamic Length
if (dataLen <= 0) or (dataLen > nMaxLength) then
begin
str := ‘‘;
Result := True;
Exit;
end;
str := StringOfChar(‘ ‘, dataLen);
(*
第二个循环读str
*)
txLen := 0;
while txLen < dataLen do
begin
rcvLen := dataLen - txLen;
if rcvLen > MAXDATALEN then rcvLen := MAXDATALEN;
rcvLen := Read(Buffer, rcvLen);
if rcvLen = 0 then
begin
sErrMsg := Format(‘只能读取字符串的%d/%d‘, [txLen, dataLen]);
Exit;
end;
Move(Buffer, str[txLen + 1], rcvLen);
Inc(txLen, rcvLen);
end;
Result := True;
except
on E: Exception do
begin
Result := false;
sErrMsg := E.Message;
end;
end;
end;

function TWinSocketStringStream.WriteString(const str: string;
var sErrMsg: string): Boolean;
var
LenBuffer: array[0..10] of byte;
sndLen, txLen, dataLen: Integer;
begin
Result := false;
sErrMsg := ‘‘;
try
(*
第一个循环写dataLen
*)
dataLen := Length(str);
Move(dataLen, LenBuffer, sizeof(dataLen));
txLen := 0;
while txLen < sizeof(dataLen) do
begin
sndLen := sizeof(dataLen) - txLen;
sndLen := Write(LenBuffer[txLen], sndLen);
if sndLen = 0 then
begin
sErrMsg := Format(‘只能写入字符串长度的%d/%d‘, [txLen, sizeof(dataLen)]);
Exit;
end;
Inc(txLen, sndLen);
end;
(*
第二个循环写str
*)
txLen := 0;
while txLen < dataLen do
begin
sndLen := dataLen - txLen;
if sndLen > MAXDATALEN then sndLen := MAXDATALEN;
sndLen := Write(str[txLen + 1], sndLen);
if sndLen = 0 then
begin
sErrMsg := Format(‘只能写入字符串的%d/%d‘, [txLen, dataLen]);
Exit;
end;
Inc(txLen, sndLen);
end;
Result := True;
except
on E: Exception do
begin
Result := false;
sErrMsg := E.Message;
end;
end;
end;

socket 通信

标签:

原文地址:http://www.cnblogs.com/lodor/p/5128877.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!