服务器端用delphi6的demo: /Internet/chat
客户端源代码:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Winsock, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function testFunc(): Integer;
function InitWSA:boolean;
function FinalizeWSA:boolean;
var
Form1: TForm1;
implementation
{$R *.dfm}
function testFunc(): Integer;
var
port: Integer;
aSocket: TSocket;
local,recipient: sockaddr_in; //接收方地址结构
sendBuffer: array [1..1024] of byte;
nSendPos: Integer;
recvBuffer: array[1..1024] of byte;
nPos: Integer;
nSeqNum: Integer;
ret: Integer;
lastTime, nowTime: Cardinal;
readfds: PFDSet;
TimeInterval: PTimeVal;
sa: sockaddr_in;
begin
result := -1;
if not(InitWSA) then exit;
aSocket := Socket(AF_INET,SOCK_STREAM,IPPROTO_IP);
recipient.sin_family := AF_INET; //协议族
recipient.sin_port := htons(WORD(6000)); //端口
recipient.sin_addr.S_addr := inet_addr(PChar('192.168.1.15')); //IP地址
//local.sin_family := AF_INET;
//local.sin_port := htons(WORD(4455));
//local.sin_addr.S_addr := inet_addr(PChar('192.168.1.15'));
if connect(aSocket, recipient, sizeof(recipient))<>0 then
begin
FinalizeWSA();
exit;
end;
//阻塞等待Agent的回应
new(readfds); //创建一个可读的等待套接字描述符集合
FD_ZERO(readfds^);
FD_SET(aSocket,readfds^);
ret := select(aSocket+1,readfds,nil,nil,nil);
closesocket(aSocket);
end;
//初始化,Socket版本协商,出错返回false;
function InitWSA:boolean;
var
aWSAData: TWSAData;
wVersionRequested: WORD;
err: Integer;
begin
wVersionRequested := MAKEWORD(1,1); //协商版本号,使用1.1版本.
err := WSAStartup(wVersionRequested,aWSAData);
if err <>0 then
begin
ShowMessage('错误:不能启动winsock动态连接库!');
result := false;
exit;
end;
//确保windows socket DLL支持1.1;
if ((LOBYTE(aWSAData.wVersion)<>1) or (HIBYTE(aWSAData.wVersion)<>1)) then
begin
ShowMessage('错误:没有对应的DLL!');
result := false;
exit;
end;
result := true;
end;
//Socket最终化,清除Winsock动态连接库,成功返回true,失败返回false
function FinalizeWSA:boolean;
begin
if WSACleanup<>0 then result := false
else result := true;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
testFunc();
end;
end.