继续上一篇:重新SOCKET API时对bind的发现
http://tb.blog.csdn.net/TrackBack.aspx?PostId=1708044
可以通过先对客户端绑定到指定端口后,再与远程的服务进行连接。至此吧,对于FTP的两种实现数据传输都已了解。下面是帖出我的实例代码:
服务端:
#pragma comment(lib,"ws2_32.lib")
#include <winsock2.h>
#include <iostream>
#include <memory.h>
#include <windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
WSAData wsaData;
if(WSAStartup(MAKEWORD(2,2),&wsaData) != 0)
{
cout<<"wsastartup fail."<<endl;
return 1;
}
SOCKET sock;
sockaddr_in addr;
sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sock == INVALID_SOCKET)
{
cout<<"socket fail."<<endl;
WSACleanup();
return 1;
}
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(5200);
if(bind(sock,(const sockaddr *)&addr,sizeof(addr)) == SOCKET_ERROR)
{
cout<<"bind fail."<<endl;
goto theend;
}
if(listen(sock,5) != 0)
{
cout<<"listen fail."<<endl;
goto theend;
}
bool bRun = true;
SOCKET sockClient;
cout<<"listening..."<<endl;
char szBuf[12];
while(bRun)
{
sockClient = accept(sock,NULL,0);
if(sockClient == INVALID_SOCKET)
{
goto theend;
}
while(1)
{
memset(szBuf,0,12);
if(recv(sockClient,szBuf,12,0) <= 0)
{
cout<<"recv fail."<<WSAGetLastError()<<endl;
goto theend;
}
cout<<"recv:"<<szBuf<<endl;
}
}
theend:
closesocket(sock);
WSACleanup();
return 0;
}
客户端:
#pragma comment(lib,"ws2_32.lib")
#include <winsock2.h>
#include <iostream>
#include <memory.h>
#include <windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
WSAData wsaData;
if(WSAStartup(MAKEWORD(2,2),&wsaData) != 0)
{
cout<<"wsastartup fail."<<endl;
return 1;
}
SOCKET sock;
sockaddr_in addr,addrs;
sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sock == INVALID_SOCKET)
{
cout<<"socket fail."<<endl;
WSACleanup();
return 1;
}
memset(&addr,0,sizeof(addr));
memset(&addrs,0,sizeof(addrs));
addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(5201);
addrs.sin_family = AF_INET;
addrs.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrs.sin_port = htons(5200);
if(bind(sock,(const sockaddr *)&addr,sizeof(addr)) == SOCKET_ERROR)
{
cout<<"bind error"<<WSAGetLastError()<<endl;
goto theend;
}
if(connect(sock,(const sockaddr *)&addrs,sizeof(addrs)) == SOCKET_ERROR)
{
cout<<"connect fail."<<WSAGetLastError()<<endl;
goto theend;
}
cout<<"connect successful."<<endl;
for(int n = 0;n<10;n++)
{
if(send(sock,"hello!!!!!",strlen("hello!!!!!"),0) == SOCKET_ERROR)
{
cout<<"send fail."<<WSAGetLastError()<<endl;
goto theend;
}
Sleep(1000 * 5);
}
theend:
closesocket(sock);
WSACleanup();
return 0;
}