C + + Socket communication

Source: Internet
Author: User
Tags htons

The following code goes from CSDN:

Server:

Server.cpp:Defines the entry point for the console application.//#include "stdafx.h"#include "winsock2.h" #pragma comment (lib, "Ws2_32.lib")#include <iostream>using namespaceStd;int _tmain (int argc, char*Argv[]) {const int buf_size = 64;            Wsadata WSD;        Wsadata variable SOCKET sserver;        Server socket socket sclient;        Client socket sockaddr_in Addrserv;;    Server address char buf[buf_size];            The receive data buffer char sendbuf[buf_size];//returns the data to the client int retVal; return value//Initialize socket dynamic Library if (WSAStartup (Makeword (2,2), &AMP;WSD)! = 0) {cout << "WSAStartup failed!" <<Endl Return 1; }//Create socket sserver =Sockets (Af_inet, Sock_stream, ipproto_tcp); if (Invalid_socket = =sserver) {cout << "socket failed!" <<Endl WSACleanup ();//release socket resources; Return-1; }//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); Close socket WSACleanup (); Release socket resources; Return-1; }//Start monitoring RetVal = Listen (sserver, 1); if (Socket_error = =RetVal) {cout << "Listen failed!" <<Endl Closesocket (sserver); Close socket WSACleanup (); Release socket resources; Return-1; }//Accept client requestsSockaddr_in addrclient; int addrclientlen = sizeof(addrclient); Sclient = Accept (Sserver, (sockaddr far*) &addrclient, &Addrclientlen); if (Invalid_socket = = sclient) {cout << "accept failed!" << Endl; closesocket (sserver);//Close Socket wsacle Anup (); Release socket resources; Return-1;} while (True) {//Receive client Data zeromemory (buf, buf_size); retVal = recv (sclient, buf, buf_size, 0); I F (socket_error = = retVal) {cout << "recv failed!" << Endl; closesocket (sserver);//Close Socket closesocket (sclient); Close socket WSACleanup (); Release socket resources; Return-1;} if (buf[0] = = ' 0 ') break; cout << "Data sent by client:" << buf <<Endl; cout << "Send data to client:" ; CIN >> sendbuf; Send (Sclient, SendBuf, strlen (SendBuf), 0);}//Exit closesocket (sserver);//Close Socket CLOSESOC Ket (sclient); Close socket WSACleanup (); Release socket resources; return 0;}                

Client:

//Client.cpp:Defines the entry point for the console application.//#include"stdafx.h"#include"winsock2.h"#include<iostream>#pragmaComment (lib, "Ws2_32.lib")using namespacestd; BOOL Recvline (SOCKET s,Char* buf);//reading a row of dataintMainintargcChar*argv[]) {    Const intBuf_size = -;            Wsadata WSD; //wsadata VariableSOCKET Shost;//Server SocketsSockaddr_in servaddr;//Server Address    CharBuf[buf_size];//Receive data buffers    CharBufrecv[buf_size]; intRetVal;//return value//initializing a nested-word dynamic library    if(WSAStartup (Makeword (2,2), &AMP;WSD)! =0) {cout<<"WSAStartup failed!"<<Endl; return-1; }        //Creating SocketsShost =sockets (Af_inet, Sock_stream, ipproto_tcp); if(Invalid_socket = =shost) {cout<<"Socket failed!"<<Endl; WSACleanup ();//releasing a socket resource        return-1; }    //Set server addressservaddr.sin_family =af_inet; ServAddr.sin_addr.s_addr= Inet_addr ("127.0.0.1"); Servaddr.sin_port= Htons (( Short)4999); intNservaddlen =sizeof(SERVADDR); //connecting to a serverRetval=connect (Shost, (LPSOCKADDR) &servaddr,sizeof(SERVADDR)); if(Socket_error = =retVal) {cout<<"Connect failed!"<<Endl;    Closesocket (Shost); //Close SocketWSACleanup ();//releasing a socket resource        return-1; }     while(true){        //sending data to the serverZeroMemory (buf, buf_size); cout<<"to send data to the server:"; CIN>>buf; RetVal= Send (Shost, buf, strlen (BUF),0); if(Socket_error = =retVal) {cout<<"Send failed!"<<Endl;    Closesocket (Shost); //Close SocketWSACleanup ();//releasing a socket resource            return-1; }        //recvline (Shost, bufrecv);Recv (Shost, BUFRECV,5,0);//Receive server-side data and receive only 5 characterscout << Endl <<"To receive data from the server:"<<Bufrecv; }    //ExitClosesocket (Shost);//Close SocketWSACleanup ();//releasing a socket resource    return 0;}

C + + Socket communication

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.