呵呵,好不容易抢了个沙发,赚点分数。贴一段代码,稍做修改即可
Function InitialTCP(IP:String;Port:Integer;ConnectType:Byte;Var NetSocket:TSocket):Integer;//Connect=0:接收;=1:发送,=2:监听
var
server:TSockAddr;
WSAData:TWSAData;
saddr,Ret:integer;
SocketVersion:Word;
hostent
hostent;
psaddr:^Longint;
begin
server.sin_port:=htons(Port);
server.sin_family:=AF_INET;//PF_INET
hostent:=GetHostbyname(PCHAR(IP));
if ConnectType<=1 then
begin
if hostent=nil then
begin
saddr:=inet_addr(pchar(IP));
if saddr<>-1 then
server.sin_addr.S_addr:=saddr;
end
else
begin
psaddr:=pointer(hostent.h_addr_list^);
server.sin_addr.S_addr:=psaddr^;
end;
end
else if ConnectType=2 then
begin
server.sin_addr.S_addr:=INADDR_ANY;//监听
end;
SocketVersion:=$101;
Ret:=WSAStartup(SocketVersion,WSAData); //初始化winsock;在windows下是必须的过程
if Ret=0 then
begin
//Memo1.Lines.Add('初始化成功!');
NetSocket:=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);//把这改成udp
If NetSocket=INVALID_SOCKET then
begin
result:=INVALID_SOCKET; // SOCKET创建失败
exit;
end
else
begin
//Memo1.Lines.Add('SOCKET创建成功');
if ConnectType<=1 then
begin
result:=CONNECT(NetSocket,server,sizeof(server));
if result=socket_error then
begin
result:=socket_error;
//Memo1.Lines.Add('SOCKET连接失败');
closesocket(NetSocket);
WSACleanup;//关闭socket
// if ret=0 then
//Memo1.Lines.Add('SOCKET释放成功!');
end;
//Memo1.Lines.Add('SOCKET连接成功!');
end
else if ConnectType=2 then
begin
result:=Bind(NetSocket,server,Sizeof(server));
if result<>0 then
begin
exit;
//Memo1.Lines.Add('绑定失败');
end;
result:=Listen(NetSocket,5);
{if result<>0 then //监听
begin
Memo1.Lines.Add('监听失败');
end;}
end;
end;
end
else
begin
SendMsgDlgMsg(IP,'CannotInitialSocket',0,2,3,0);
result:=-1;
end;
end;