1. 程式人生 > >通過指定的埠進行遠端連線

通過指定的埠進行遠端連線

 繼續上一篇:重新SOCKET API時對bind的發現

可以通過先對客戶端繫結到指定埠後,再與遠端的服務進行連線。至此吧,對於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;
}