winsok编程 ( 积分: 0 )

  • 主题发起人 主题发起人 ilmm520
  • 开始时间 开始时间
I

ilmm520

Unregistered / Unconfirmed
GUEST, unregistred user!
问下高手们,如何用use winsok<br>单元来写简单的网络程序!<br>winsok。属性太多了
 
问下高手们,如何用use winsok<br>单元来写简单的网络程序!<br>winsok。属性太多了
 
哪有具体的东西可以看
 
用winsock2(delphi无,需要调用windows-&gt;dll).<br>1,初始化winsock 2,设定网卡 3,绑定ip 4,设置工作方式 5,用几线程不停的读。大致就这样吧。
 
有没有相关的代码说明呢
 
一个非常简单的用api写的socket读写过程, 它连接本机1000端口, 成功的话发送一个字符串&quot;Hello World!&quot;, 然后从服务器接收最多1k数据并用showmessage显示收到的内容, 最后关闭连接:<br>uses<br> &nbsp;winsock, ...;<br>var<br> &nbsp;wdata: TWSAData;<br> &nbsp;Sock: Integer;<br> &nbsp;Addr: TSockAddrIn;<br> &nbsp;sendbuf: string;<br> &nbsp;recvbuf: string;<br> &nbsp;l: Integer;<br>begin<br> &nbsp;WSAStartup($0101, wdata); &nbsp; &nbsp;// 初始化 winsock 1.1<br> &nbsp;Sock := Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); &nbsp;// 创建 socket<br> &nbsp;try<br> &nbsp; &nbsp;if Sock &gt; 0 then<br> &nbsp; &nbsp;begin<br> &nbsp; &nbsp; &nbsp;{初始化要连接的地址}<br> &nbsp; &nbsp; &nbsp;Addr.sin_family := 2;<br> &nbsp; &nbsp; &nbsp;Addr.sin_addr.s_addr := inet_addr('127.0.0.1');<br> &nbsp; &nbsp; &nbsp;Addr.sin_port := htons(1000); &nbsp; &nbsp;// 端口1000<br> &nbsp; &nbsp; {建立连接}<br> &nbsp; &nbsp; &nbsp;if connect(sock, addr, sizeof(addr)) then<br> &nbsp; &nbsp; &nbsp;begin<br> &nbsp; &nbsp; &nbsp; &nbsp;sendbuf := 'Hello World!';<br> &nbsp; &nbsp; &nbsp; &nbsp;// 发送数据<br> &nbsp; &nbsp; &nbsp; &nbsp;if send(sock, sendbuf[1], length(sendbuf), 0) &lt; 0 then<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;raise exception.create('错误');<br> &nbsp; &nbsp; &nbsp; &nbsp;setlength(recvbuf, 1024); &nbsp; &nbsp;// 设置接收缓冲区<br> &nbsp; &nbsp; &nbsp; // 准备接收数据<br> &nbsp; &nbsp; &nbsp; &nbsp;l := recv(sock, recvbuf[1], length(recvbuf), 0); &nbsp;// 最多一次接受1k数据<br> &nbsp; &nbsp; &nbsp; &nbsp;if l &gt; 0 then<br> &nbsp; &nbsp; &nbsp; &nbsp;begin<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;setlength(recvbuf, l);<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;showmessage(recvbuf);<br> &nbsp; &nbsp; &nbsp; &nbsp;end;<br> &nbsp; &nbsp; &nbsp;end;<br> &nbsp; &nbsp;end;<br> &nbsp;finally<br> &nbsp; &nbsp;closesocket(sock);<br> &nbsp; &nbsp;wsacleanup;<br> &nbsp;end;<br>end;
 
后退
顶部