请教各位网友,问个socket的问题:(10分)

  • 主题发起人 主题发起人 netbug
  • 开始时间 开始时间
N

netbug

Unregistered / Unconfirmed
GUEST, unregistred user!
我这里有个LAN,并有用TCP/IP协议。我用Delphi做了两个程序,分别是server与client,请看:<br>一:server:<br>var<br>err,i,j:integer;<br>wd:wsadata;<br>sk:tsocket;<br>ar:sockaddr_in;<br>begin<br>&nbsp;err:=wsastartup(2,wd);<br>&nbsp;if err=0 then<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; begin &nbsp;edit1.text:=inttostr(wd.wVersion);<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; end;<br>&nbsp; sk:=socket(PF_INET,SOCK_STREAM, 0);<br>&nbsp; if sk&lt;&gt;INVALID_SOCKET then<br>&nbsp; edit2.text:=inttostr(sk);<br>&nbsp; ar.sin_family:=PF_INET;<br>&nbsp; ar.sin_port:=6123;<br>&nbsp; ar.sin_addr.S_addr:=INADDR_ANY;<br>&nbsp; i:=bind(sk,ar,sizeof(ar));<br>&nbsp; edit3.Text:=inttostr(i);<br>&nbsp; j:=listen(sk,1);<br>&nbsp; edit4.Text:=inttostr(j);<br>end;<br>二:client:<br>var err1,i,j,k:integer;<br>wd:wsadata;<br>sk1:tsocket;<br>ar1:sockaddr_in;<br>begin<br>&nbsp;err1:=wsastartup(2,wd);<br>&nbsp;if err1=0 then<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; begin &nbsp;edit1.text:=inttostr(wd.wVersion);<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; end;<br>&nbsp;sk1:=socket(PF_INET,SOCK_STREAM, 0);<br>&nbsp; if sk1&lt;&gt;INVALID_SOCKET then<br>&nbsp; edit2.text:=inttostr(sk1);<br>&nbsp; ar1.sin_family:=PF_INET;<br>&nbsp; ar1.sin_addr.S_un_b.s_b1:=chr(192);<br>&nbsp; ar1.sin_addr.S_un_b.s_b2:=chr(1);<br>&nbsp; ar1.sin_addr.S_un_b.s_b3:=chr(1);<br>&nbsp; ar1.sin_addr.S_un_b.s_b4:=chr(100);<br>&nbsp; ar1.sin_port:=6123;<br>&nbsp; i:=connect(sk1,ar1,sizeof(ar1));<br>&nbsp; j:=wsagetlasterror();<br>&nbsp; edit3.text:=inttostr(i);<br>&nbsp; edit4.Text:=inttostr(j);<br>end;<br>我把server程序考在一台IP为192.1.1.100的机上,并运行。<br>然后在另一台机上运行client,第一次运行client,发现<br>有连上(i:=connect(sk1,ar1,sizeof(ar1))中的i为0),<br>但第二次运行client,就发现不成功(我的server程序<br>没有退出,一直在那运行,并i:=connect(sk1,ar1,sizeof(ar1))<br>中的i为-1),请问:我的程序错在哪?要如何更改?<br>(我需要server程序在不退出的请况下,在client端试图<br>去连接server,为以后的端口搜索做准备)<br>另:在数据类型为sockaddr_in的数据中sin_family是指什么?<br>在服务器端与客户器端它的含义是啥?取PF_INET是指什么?<br>是不是还有别的取直?<br>再:我的IP地址写法:<br>&nbsp; ar1.sin_addr.S_un_b.s_b1:=chr(192);<br>&nbsp; ar1.sin_addr.S_un_b.s_b2:=chr(1);<br>&nbsp; ar1.sin_addr.S_un_b.s_b3:=chr(1);<br>&nbsp; ar1.sin_addr.S_un_b.s_b4:=chr(100);<br>有没有错?<br>谢谢。<br>
 
i=-1不一定是连接错误,可以用WSAGetLastError看看错误代码是否<br>WSAEWOULDBLOCK。你看看connect的帮助吧<br>
 
为甚麽不用delphi 的控件,很好用的!基本上可以你的目的.
 
粗略看看,你的server好象有问题(不确切)<br>请再仔细查查。
 
如果为了使用,直接用 Delphi 的控件没问题!<br>如果出于学习,可以看 Delphi 的源程序!
 
接受答案了.
 
后退
顶部