Windows下C++ Socket编程

Socket编程有三种:流式套接字(SOCK_STREAM),数据包套接字(SOCK_DGRAM),原始套接字(SOCK_RAW),基于TCP的Socket编程采用流式套接字。下面分别介绍Server和Client端的编程步骤:

Server端:

1.加载套接字,创建套接字(WSAStartup()/socket)

2.绑定套接字到一个IP地址和端口(bind());

3.将套接字设置为监听模式等待请求连接(listen())

4. 请求到来后,接受连接请求,返回一个新的对应于此次连接的套接字(accept());

5. 用返回的套接字和Client进行通信(send()/recv())

6. 返回,等待另一连接请求

7. 关闭套接字,关闭加载的套接字库(closesocket()/WSAClean())

 

客户端编程的步骤:

 

1:加载套接字库,创建套接字(WSAStartup()/socket())

 

2:向服务器发出连接请求(connect())

 

3:和服务器端进行通信(send()/recv())

 

4:关闭套接字,关闭加载的套接字库(closesocket()/WSACleanup())

运行:

先运行Server,在运行Client,这就是简单的C/S传输。

Server代码如下:

// Server.cpp : Defines the entry point for the console application.  
//  
#include "winsock2.h"  
#pragma comment(lib, "ws2_32.lib")  
#include   
using namespace std;  
int main(int argc, char* argv[])  
{  
    const int BUF_SIZE = 64;  
    WSADATA         wsd;            //WSADATA Variable  
    SOCKET          sServer;        //Server socket  
    SOCKET          sClient;        //Client socket  
    SOCKADDR_IN     addrServ;;      //Serevr address
    char            buf[BUF_SIZE];  //Receiving data buffer area   
    char            sendBuf[BUF_SIZE];//Return data to client
    int             retVal;         //Return value 
    //Initial socket dynamic lib  
    if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)  
    {  
        cout << "WSAStartup failed!" << endl;  
        return 1;  
    }  
      
    //Create socket 
    sServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);      
    if(INVALID_SOCKET == sServer)  
    {  
        cout << "socket failed!" << endl;  
        WSACleanup();//Release socket resource 
        return  -1;  
    }  
      
    //Set server socket address  
    addrServ.sin_family = AF_INET;  
    addrServ.sin_port = htons(4999);  
    addrServ.sin_addr.s_addr = INADDR_ANY;        
    //bind socket  
    retVal = bind(sServer, (LPSOCKADDR)&addrServ, sizeof(SOCKADDR_IN));  
    if(SOCKET_ERROR == retVal)  
    {     
        cout << "bind failed!" << endl;  
        closesocket(sServer);   
        WSACleanup();          
        return -1;  
    }  
      
    //Starting listening
    retVal = listen(sServer, 1);  
    if(SOCKET_ERROR == retVal)  
    {  
        cout << "listen failed!" << endl;         
        closesocket(sServer);   
        WSACleanup();           
        return -1;  
    }  
      
    //Receiving request from client
    sockaddr_in addrClient;  
    int addrClientlen = sizeof(addrClient);  
    sClient = accept(sServer,(sockaddr FAR*)&addrClient, &addrClientlen);  
    if(INVALID_SOCKET == sClient)  
    {  
        cout << "accept failed!" << endl;         
        closesocket(sServer);  
        WSACleanup();           
        return -1;  
    }  
      
    while(true)  
    {  
        //Receiving client data
        ZeroMemory(buf, BUF_SIZE);  
        retVal = recv(sClient, buf, BUF_SIZE, 0);  
        if (SOCKET_ERROR == retVal)  
        {  
            cout << "recv failed!" << endl;       
            closesocket(sServer);   
            closesocket(sClient);       
            WSACleanup();           
            return -1;  
        }  
        if(buf[0] == '0')  
            break;  
        cout << "The date of sending by client: " << buf <> sendBuf;  
          
        send(sClient, sendBuf, strlen(sendBuf), 0);  
    }  
      
    //退出  
    closesocket(sServer);   
    closesocket(sClient);   
    WSACleanup();           
      
    return 0;  
}  

Client 代码如下:

#include "winsock2.h"  
#include   
#pragma comment(lib, "ws2_32.lib")  
  
using namespace std;  
BOOL RecvLine(SOCKET s, char* buf); //Read the data of a line  
  
int main(int argc, char* argv[])  
{  
	const int BUF_SIZE = 64;  
    WSADATA wsd; //WSADATA Variable  
    SOCKET sHost; //Server socket
    SOCKADDR_IN servAddr; //Server Address  
    char buf[BUF_SIZE]; //Receiving data buffer area 
    char bufRecv[BUF_SIZE];  
    int retVal; //return value  
    //Initial socket dynamic lib
   if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)  
   {  
	   cout << "WSAStartup failed!" << endl;  
       return -1;  
   }  
   //Create socket  
   sHost = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  
   if(INVALID_SOCKET == sHost)  
   {  
	   cout << "socket failed!" << endl;  
       WSACleanup();//Release socket resource  
       return  -1;  
   }  
   //Set server address 
   servAddr.sin_family =AF_INET;  
   servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");  
   servAddr.sin_port = htons((short)4999);  
   int nServAddlen  = sizeof(servAddr);  
  
   //Connect Server 
   retVal=connect(sHost,(LPSOCKADDR)&servAddr, sizeof(servAddr));  
   if(SOCKET_ERROR == retVal)  
   {  
	   cout << "connect failed!" << endl;  
       closesocket(sHost); //close socket 
       WSACleanup(); //Release socket resource   
       return -1;  
   }  
   while(true)  
   {  
	   //Sending data to the Server 
       ZeroMemory(buf, BUF_SIZE);  
       cout << " Sending data to the Server:  ";  
       cin >> buf;  
       retVal = send(sHost, buf, strlen(buf), 0);  
       if (SOCKET_ERROR == retVal)  
       {  
		   cout << "send failed!" << endl;  
           closesocket(sHost);  
           WSACleanup();  
           return -1;  
       }  
       //RecvLine(sHost, bufRecv);  
       ZeroMemory(bufRecv, BUF_SIZE);  
       recv(sHost, bufRecv,BUF_SIZE , 0); // Accepting data from Server,only receiving 5 characters 
       cout << endl <<"Accepting data from Server: "<< bufRecv;  
       cout<



你可能感兴趣的:(Windows下C++ Socket编程)