在编制Winsocket程序的时候,要有一些必要的步骤:
1、初始化Winsock动态连接库;
2、建立一个Winsock对象。
3、连接主机。
4、和主机进行数据交流。
5、关闭Socket对象
6、释放Winsoket动态链接库。
下面是一个使用winsock Api实现finger实现的源程序:在delphi6中调试通过。
unit finger;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,winsock, StdCtrls;
type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; edtHost: TEdit; btnFinger: TButton; edtUser: TEdit; memInfo: TMemo; procedure btnFingerClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } public { Public declarations } end;
var Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnFingerClick(Sender: TObject); var Info:string;//服务器返回的用户信息 BufSend,BufRev:pChar;//中间信息 skt:TSOCKET;//创建Socket对象 addr:TSockAddr;//地址信息 Re:Integer; begin //1、建立Socket skt:=socket(AF_INET,SOCK_STREAM,0); if(skt=INVALID_SOCKET)Then begin memInfo.Lines.Add(''''Error:Create Winsock Failed''''); exit; end; //2、连接主机 ZeroMemory(@addr,sizeof(addr)); Addr.sin_family:=AF_INET; Addr.sin_addr.S_addr:=inet_addr(Pchar(edtHost.Text)); //开放79端口 addr.sin_port:=htons(79); Re:=connect(skt,addr,sizeof(addr)); if(Re<>0)then begin memInfo.Lines.Add(''''Connect to Server Failed!''''); exit; end;
//3、发送信息 GETMem(BufSend,1024); ZeroMemory(BufSend,1024); Info:=edtUser.Text+#10; StrPCopy(BufSend,info); Re:=Send(skt,Bufsend^,Length(BufSend),0); if(Re=SOCKET_ERROR)then begin memInfo.Lines.Add(''''Send Data Failed!''''); exit; end; //5、读取主机返回信息 GetMem(BufRev,1024); Repeat ZeroMemory(BufRev,1024); re:=recv(skt,BufRev^,1024,0); Info:=Strpas(bufRev); memInfo.Lines.Add(Info); Until re=0; memInfo.Lines.Add(''''FINISH!''''); FreeMem(BufSend); FreeMem(BufRev); //6、关闭socket连接 closesocket(skt); end;
procedure TForm1.FormCreate(Sender: TObject); var WSAData:TWSAData; //是TWSAData类型的变量,系统把加载的版本信息添加到这个结构中 begin //初始化Winsock if(WSAStartup(MAKEWORD(2,0),WSAData)<>0)then begin //初始化失败 memInfo.Lines.Add(''''Winsock Init Failed!''''); exit; end else memInfo.Lines.Add(''''Winsock Start!''''); end;
procedure TForm1.FormDestroy(Sender: TObject); begin WSACleanUP(); end;
end. 如果有什么问题,请联系 qiujianben@163.com (杭州电子工业学院)
[VB.NET程序]Auto Complete combo Box(VB.NET Source Use API… [VB.NET程序]在 VB 中使用 Unicode API [VB.NET程序]API 更改系统菜单条目 [VB.NET程序]在VB中调用Windows API的注意事项 [VB.NET程序]vb调用winInet API接口post数据到指定的url [VB.NET程序]如 何 用 API 播 放 CD [VB.NET程序]VB5.0与Windows API 间的呼叫技巧 [VB.NET程序]在VB6中用WINDOWS API函数读写INI文件 [VB.NET程序]Visual Basic调用Windows API函数的应用举例 [VB.NET程序]VB + API 获取 IE 的 代理服务器 配制
|