unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, WinSock,
StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Memo2: TMemo;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
procedure RecvMessage(var Msg: TMessage); message WM_USER + 1;
public
{ Public declarations }
end;
var
Form1: TForm1;
RemoteHost: string;
RemotePort: Integer;
ClientSocket: Integer;
implementation
{$R *.DFM}
{线程处理函数}
function RecvProc(P: Pointer): DWORD;
var
Buffer: PChar;
ret: Integer;
begin
while True do
begin
ret := recv(ClientSocket, Buffer, sizeof(Buffer), 0);
if ret = 0 then
begin
ShowMessage('Socket closed.');
Break;
end
else
if ret = SOCKET_ERROR then
begin
ShowMessage('Read Error.');
Break;
end;
GetMem(Buffer, ret);
SendMessage(HWND(P), WM_USER + 1, 0, Integer(Buffer));
end;
closesocket(ClientSocket);
ClientSocket := INVALID_SOCKET;
Result := WSAGetLastError;
end;
procedure ShowError;
var
ErrorCode: Integer;
begin
ErrorCode := WSAGetLastError;
ShowMessage('Error: ' + IntToStr(ErrorCode));
end;
procedure TForm1.Button1Click(Sender: TObject);
var
sa_in_svr: sockaddr_in;
tid: Cardinal;
begin
sa_in_svr.sin_family := AF_INET;
sa_in_svr.sin_port := htons(RemotePort);
sa_in_svr.sin_addr.S_addr := htonl(inet_addr(PChar(RemoteHost)));
{连接到服务器}
if connect(ClientSocket, sa_in_svr, sizeof(sockaddr_in)) = SOCKET_ERROR then
begin
closesocket(ClientSocket);
ClientSocket := INVALID_SOCKET;
ShowMessage('Failed to connect to server.');
end
else
begin
{创建接收数据线程}
CreateThread(nil, 0, @RecvProc, Pointer(Handle), 0, tid);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
WSData: WSAData;
ErrorCode: Integer;
sa_in: sockaddr_in;
begin
RemoteHost := '127.0.0.1';
RemotePort := 2000;
{初始化WinSock}
if WSAStartup(MakeWord(1, 1), WSData) <> 0 then
begin
ShowMessage('WinSock initialization fialed.');
Exit;
end;
ClientSocket := socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ClientSocket = INVALID_SOCKET then
begin
ShowError;
Exit;
end;
sa_in.sin_family := AF_INET;
sa_in.sin_port := htons(0);
sa_in.sin_addr.S_addr := INADDR_ANY;
if bind(ClientSocket, sa_in, sizeof(sockaddr_in)) = SOCKET_ERROR then
begin
closesocket(ClientSocket);
ClientSocket := INVALID_SOCKET;
ShowError;
end;
end;
procedure TForm1.RecvMessage(var Msg: TMessage);
var
P: PChar;
begin
P := PChar(Msg.LParam);
Memo2.Text := String(P);
FreeMem(P);
end;
procedure TForm1.Button2Click(Sender: TObject);
var
buf: PChar;
len: Integer;
begin
buf := PChar(Memo1.Text);
len := Length(Memo1.Text);
send(ClientSocket, buf, len, 0);
end;
end.
程序退出时别忘调用WSACleanup
这是别人的你参考一下吧。