Socket programming uses C + + to implement server-side and client-side

Source: Internet
Author: User
Tags htons

I created two projects on Visual Stdio 2013, compiled the following two main files separately, and then tested the

Service side: Server.cpp
#include <winsock2. H>#include <iostream>using STD::cout;using STD::Cin;using STD:: Endl;#include <string>using STD::string;#pragma comment (lib, "Ws2_32.lib")voidMain () {//Create socketsWORD myversionrequest; Wsadata Wsadata;//contains Winstock version information supported by the systemMyversionrequest = Makeword (1,1);//Initialize version 1.1    intErr Err = WSAStartup (myversionrequest, &wsadata);if(!err) {printf("Open socket \ n"); }Else{//Further binding sockets        printf("The nested word is not open!");return; } Socket Sersocket = socket (af_inet, Sock_stream,0);//Create a recognizable socket    //parameters that need to be boundSockaddr_in addr;    addr.sin_family = af_inet; Addr.sin_addr. S_un. S_ADDR = htonl (Inaddr_any);//IP AddressAddr.sin_port = htons ( the);//Bound Port    //Bind the socket to the specified network addressBind (Sersocket, (sockaddr*) &addr,sizeof(SOCKADDR));//Bind completeListen (Sersocket,Ten);//The second parameter represents the maximum number of connections that can be receivedSockaddr_in Clientsocket;intLen =sizeof(SOCKADDR); SOCKET Serconn;//Waiting for the client to connectSerconn = Accept (Sersocket, (sockaddr*) &clientsocket, &len);cout<<"Client"<< Inet_ntoa (CLIENTSOCKET.SIN_ADDR) <<"Connected"<< Endl;//client is connected     while(1) {Charsendbuf[ -];sprintf(SendBuf,"Server:welcome%s to server.", Inet_ntoa (CLIENTSOCKET.SIN_ADDR));//Find the corresponding IP and print the line to thereSend (Serconn, SendBuf,strlen(SENDBUF) +1,0);Charreceivebuf[ -];//Receive information from clientsRecv (Serconn, ReceiveBuf,strlen(RECEIVEBUF) +1,0);Char* quit ="Quit";//If the client has a quit signal, the server shuts down and the client shuts down        if(!strcmp(ReceiveBuf, quit)) { Break; }printf("%s\n", RECEIVEBUF); } closesocket (Serconn);//OffWSACleanup ();//release of resource operations}
Client: Client.cpp
#include <winsock2. H>#include <iostream>using STD::cout;using STD::Cin;using STD:: Endl;#include <string>using STD::string;#include <conio.h>#pragma comment (lib, "Ws2_32.lib")voidMain () {intErr    WORD versionrequired; Wsadata Wsadata;//contains Winstock version information supported by the systemversionrequired = Makeword (1,1);//Initialize version 1.1    //Register Winstock, return statusErr = WSAStartup (versionrequired, &wsadata);//Protocol library version Information    if(!err)//Return result of 0 indicates initialization failed{cout<< LPSTR ("Client socket has been opened!\n"); }Else{//Call WSAGetLastError () to view error messages        cout<< ("Client socket Open failed:") << WSAGetLastError () << Endl;return;//End}/ * Create socket: Streaming socket: sock_stream, IPPROTO_TCP datagram socket: SOCK_DGRAM, IPPROTO_UDP */Socket clientsocket = socket (af_inet, sock_stream, ipproto_tcp);//Create a streaming socketSockaddr_in clientsock_in;//Winsock address structure specifically for the Internet communications domainClientsock_in.sin_addr. S_un. S_ADDR = inet_addr ("127.0.0.1");//Specify the host IP address of the socket via the INET_ADDR structureclientsock_in.sin_family = af_inet;//Designated protocol family: Af_inetClientsock_in.sin_port = htons ( the);//Specify the port number of the transport layer that will be assigned to the socket: 6000    intFail = Connect (Clientsocket, (sockaddr*) &clientsock_in,sizeof(SOCKADDR));//Start connection    if(fail) {cout<<"Connection to server failed!" Program will exit ... "<< Endl; _getch ();return; }stringS while(Cin>> s) {Charreceivebuf[ -];//Receive DataRecv (Clientsocket, ReceiveBuf,101,0);cout<< ReceiveBuf <<endl;//Send dataSend (Clientsocket, S.c_str (), s.length () +1,0);if(s = ="Quit"){ Break; }} closesocket (Clientsocket);//Close socket    if(WSACleanup () = = Socket_error) {cout<<"Socket shutdown failed:"<< WSAGetLastError () << Endl; }Else{cout<<"The socket was successfully closed."<< Endl; } _getch ();return;}//INET_ADDR Structure:/*struct in_addr {union{struct{U_char s_b1, S_b2, S_b3, S_B4;} S_un_b; struct{u_short s_w1, S_W2;} S_un_w; U_long s_addr;}} */
Note:

    • Unable to support Chinese data transfer (garbled);
    • When the client enters data with a space, it is treated as multiple input data (because it is the data read with CIN)

    Socket programming uses C + + to implement server-side and client-side

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.