用WINSOCKS API 函数进行通讯。函数功能详见DELPHI帮助。<br>unit <br>uses<br> winsock,...;//winsock单元可在delphi目录中找到。<br><br>var<br> Form1: TForm1;<br> xl_socket:Tsocket;<br><br>implementation<br><br>procedure TForm1.Button1Click(Sender: TObject);<br>VAR<br>XL_VERSION:WORD;<br>XL_WSADATA:tWSADATA;<br>RET:INTEGER;<br>hostname:string;<br>server_port:integer;<br>xl_hostent
hostent;<br>xl_sockaddrin:TSOCKADDRIN;<br>psaddr:^longint;<br>saddr:integer;<br>begin<br> server_port:=8080;<br> hostname:='111.111.111.111';<br> xl_sockaddrin.sin_port:=htons(server_port);<br> xl_sockaddrin.sin_family:=PF_INET;<br> xl_hostent:=gethostbyname(PCHAR(HOSTNAME));<br> IF xl_hostent=nil then<br> begin<br> saddr:=inet_addr(pchar(hostname));<br> if saddr<>-1 then<br> xl_sockaddrin.sin_addr.S_addr:= saddr;<br> end<br> ELSE<br> BEGIN<br> psaddr:=pointer(xl_hostent.h_addr_list^);<br> xl_sockaddrin.sin_addr.S_addr:=psaddr^;<br> END;<br> XL_VERSION:=$101;<br> RET:=WSASTARTUP(XL_VERSION,XL_WSADATA);<br> IF RET=0 THEN<br> BEGIN<br> APPLICATION.MessageBox(初始化成功','注意',mb_ok);<br> xl_socket:=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);<br> IF XL_SOCKET=INVALID_SOCKET THEN<br> APPLICATION.MessageBox('SOCKET创建失败','注意',mb_ok)<br> else<br> begin<br> APPLICATION.MessageBox('SOCKET创建成功','注意',mb_ok);<br> RET:=CONNECT(xl_socket,xl_sockaddrin,sizeof(xl_sockaddrin));<br><br> if ret=socket_error then<br> begin<br> APPLICATION.MessageBox('SOCKET连接失败','注意',mb_ok);<br> ret:=closesocket(xl_socket);<br> if ret=0 then<br> APPLICATION.MessageBox('SOCKET释放成功!','注意',mb_ok);<br> end<br> else<br> begin<br> APPLICATION.MessageBox('SOCKET连接成功!','注意',mb_ok);<br> button2.Enabled:=true;<br> button3.Enabled:=true;<br> exit;<br> end;<br> end;<br> WSAcleanup;<br> END;<br><br>procedure TForm1.Button3Click(Sender: TObject);//发送<br>var<br>ret,len:integer;<br>s:string;<br>psend
char;<br>begin<br> s:=memo1.text;<br> len:=length(s);<br> Psend:=stralloc(LEN);<br> STRPCOPY(Psend,S);<br> ret:=send(xl_socket,Psend^,len,0);<br> if ret<>SOCKET_ERROR then<br> application.MessageBox('发送成功','注意',mb_ok)<br> else<br> application.MessageBox('发送失败','注意',mb_ok);<br>end;<br><br>