delphi 里API实现Socket简单例子
unit testEchoMain;interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Winsock, ExtCtrls, StdCtrls, ComCtrls;
type
TfrmMain = class(TForm)
edtSend: TEdit;
Label1: TLabel;
btnSend: TButton;
edtPort: TEdit;
edtHostIP: TEdit;
Label4: TLabel;
Label3: TLabel;
Bevel1: TBevel;
edtEcho: TEdit;
Label5: TLabel;
btnConnect: TButton;
btnDisConnect: TButton;
StatusBar1: TStatusBar;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnConnectClick(Sender: TObject);
procedure btnDisConnectClick(Sender: TObject);
procedure btnSendClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
socket1:TSocket;
implementation
{$R *.DFM}
procedure TfrmMain.FormCreate(Sender: TObject);
var
WSAData:TWSAData;
begin
//初始化Socket
if (WSAStartup(MAKEWORD(2,0),WSAData)<>0) then
begin
//初始化失败
StatusBar1.SimpleText:='Init Failed';
exit;
end
else
StatusBar1.SimpleText:='Init Success';
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
//释放winsock
WSACleanUP();
end;
procedure TfrmMain.btnConnectClick(Sender: TObject);
var
SocketAddr:TSockAddr;
Re:Integer;
begin
//建立socket
socket1:=socket(AF_INET,SOCK_STREAM,0);
if(socket1=INVALID_SOCKET)then
begin
StatusBar1.SimpleText:='错误:建立socket失败';
exit;
end;
//连接主机
ZeroMemory(@SocketAddr,sizeof(SocketAddr));
SocketAddr.sin_family :=AF_INET;
SocketAddr.sin_addr.s_addr :=inet_addr(Pchar(edtHostIP.Text));
SocketAddr.sin_port:=htons(StrToInt(edtPort.Text));
Re := connect(socket1,SocketAddr,sizeof(SocketAddr));
if(Re<>0)then
begin
StatusBar1.SimpleText:='连接服务器失败';
exit;
end;
//连接主机成功
StatusBar1.SimpleText:='连接主机成功';
end;
procedure TfrmMain.btnDisConnectClick(Sender: TObject);
var
re,err:integer;
info:string;
begin
// 关闭
re:=closesocket(socket1);
// 判断关闭socket结果
if re=SOCKET_ERROR then
begin
err:=WSAGetLastError();
case err of
WSANOTINITIALISED:info:='请先调用WSAStartup';
WSAENETDOWN:info:='网络子系统失败';
WSAENOTSOCK:info:='描述符不是socket对象';
WSAEINPROGRESS:info:='Socket忙';
WSAEINTR:info:='通过WSACancelBlockingCall取消操作';
WSAEWOULDBLOCK:info:='超时值过大';
end;
end
else
Info:='成功关闭socket';
StatusBar1.SimpleText:=info;
end;
procedure TfrmMain.btnSendClick(Sender: TObject);
var
Info:string;
BufSend,BufRecv:pchar;
Re:Integer;
begin
//发送消息
GetMem(BufSend,1024);
ZeroMemory(BufSend,1024);
Info:=edtSend.Text;
StrPCopy(BufSend,Info);
Re:=send(socket1,BufSend^,Length(BufSend),0);
if(Re=SOCKET_ERROR)then
begin
StatusBar1.SimpleText:='发送数据失败';
exit;
end;
//接收消息
GetMem(BufRecv,1024);
ZeroMemory(bufRecv,1024);
re := recv(socket1, BufRecv^, 1024, 0);
Info:=StrPas(bufRecv);
edtEcho.Text:=Info;
//释放pchar变量
FreeMem(BufSend);
FreeMem(BufRecv);
end;
end. 這個,貌似可以拿來做轉發吧?
页:
[1]