C++socket Communication (client and server)

Source: Internet
Author: User
Tags htons

Win32 Console Edition

Get the native IP:

Cmd:ipconfig/all

I am writing a server and client point-to-point information Transfer (implementing mutual code that can be changed appropriately):

The server sent to the client is a struct-body data

struct Date {    float  M1;     float m2;     float m3;     float M_roll;     float M_pitch;     float M_rotate;} DataBlock;

On the server code (blocking):

#include"stdafx.h"#include<iostream>#include<string>#include<winsock2.h>#pragmaComment (lib, "Ws2_32.lib")usingstd::cout;usingstd::cin;usingSTD::string;usingStd::endl;typedefstructDate {floatM1; floatm2; floatm3; floatM_roll; floatM_pitch; floatM_rotate;} DataBlock;intMain () {cout<<"Server started! ....."<<Endl; //Initialize WinsockWsadata WsaD; WSAStartup (Makeword (1,1), &WsaD); //creating a listening socketSOCKET Slisten =sockets (Af_inet, Sock_stream, ipproto_tcp); //binding host addresses and listening sockets    structSockaddr_in my_addr;//Host Addressmy_addr.sin_family =af_inet; My_addr.sin_port= Htons (8088);//Specify PortMY_ADDR.SIN_ADDR.S_ADDR =htonl (Inaddr_any); Bind (Slisten, (structSOCKADDR *) &my_addr,sizeof(MY_ADDR)); //Start MonitoringListen (Slisten,5);//5 is the maximum number of connections//Start receiving data    structSockaddr_in c_addr;//Customer Address    intAddr_len =sizeof(C_ADDR); SOCKET Sconnect= Accept (Slisten, (structsockaddr*) &c_addr, &addr_len);//Create a connection socket from a listening socketcout<<"Connection established ..."<<Endl; Charbuf[ -];  while(true) {DataBlock client_send; cout<<"Enter (start) to start the change, enter (end) to end the service:"<<Endl; cout<<"enter what to send:";  while(Cin.getline (BUF, -))        {            stringRcover =buf; if(Rcover = ="End") Break; if(Rcover = ="Start") {cout<<"Please enter data in m1-m2-m3-m_roll-m_pitch-m_rotate format:"<<Endl; Chartransmit[ -]; Cin.getline (Transmit, -); Send (Sconnect, transmit, strlen (transmit)+1,0);//The string also has an end flagmemset (Transmit,0,sizeof(transmit)); }                    }        return 0; }

Client: (non-blocking)

The first thing to do is to have a macro (usually in the header file area of the. h file)

#include"stdafx.h"#include<iostream>#include<string>#include<cstring>#include<winsock2.h>#include<WS2tcpip.h>#include<vector>#include<sstream>#pragmaComment (lib, "Ws2_32.lib")using namespaceStd;typedefstructDate {floatM1; floatm2; floatm3; floatM_roll; floatM_pitch; floatM_rotate;} DataBlock;voidSplitex (vector<string>&strs,Const string& SRC,stringseparate_character) {    intSeparate_characterlen = Separate_character.size ();//splits the length of the string so that it can support delimiters like ",," multi-string    intLastposition =0, index =-1;  while(-1! = (Index =Src.find (Separate_character, lastposition))) {Strs.push_back (Src.substr (lastposition, index-lastposition)); Lastposition= index +Separate_characterlen; }    stringlaststring = Src.substr (lastposition);//Capture the contents of the last delimiter    if(!laststring.empty ()) Strs.push_back (laststring);//If there is content after the last delimiter, queue up.}floatStr_float (stringa) {floatb;                              StringStream SS; //string goto intSS <<A; SS>>b; returnb;}intMain () {cout<<"Client Startup"<<Endl; //Initialize WinsockWsadata WsaD; WSAStartup (Makeword (1,1), &WsaD); //creating a Client socketSOCKET sclient =sockets (Af_inet, Sock_stream, ipproto_tcp); //connecting to a serverU_long IMode =1;//if set to 0, this is a block -Ioctlsocket (Sclient, Fionbio, &IMode); structsockaddr_in servaddr; Servaddr.sin_family=af_inet; cout<<"Please enter the LAN IP address:"<<Endl; stringIPAddress; CIN>>IPAddress; cout<<IPAddress; Servaddr.sin_addr.s_addr= Inet_addr (Ipaddress.c_str ());//Specify the serverServaddr.sin_port = htons (8088);//Specify Portcout << endl<<"OK"<<Endl; Connect (sclient, (structsockaddr*) &servaddr,sizeof(SERVADDR));//connecting hosts via sockets            Charbuf[ -];        DataBlock Resu_data;  while(true) {            //Store the received characters            intLen = recv (sclient, buf,sizeof(BUF),0);//receiving data through a connection socket                        if(Len >0) {vector<string>result; cout<<"customer says:"<< buf <<Endl; stringTest =buf; cout<< Test <<Endl; Splitex (result, test,"-"); RESU_DATA.M1= Str_float (result[0]); RESU_DATA.M2= Str_float (result[1]); RESU_DATA.M3= Str_float (result[2]); Resu_data.m_roll= Str_float (result[3]); Resu_data.m_pitch= Str_float (result[4]); Resu_data.m_rotate= Str_float (result[5]); cout<< resu_data.m1 <<Endl; cout<< resu_data.m2 <<Endl; cout<< resu_data.m3 <<Endl; cout<< Resu_data.m_roll <<Endl; cout<< resu_data.m_pitch<<Endl; cout<< resu_data.m_rotate <<Endl; }                }                return 0;}

This is a point-to-point, first open server, and then open the client.

C++socket Communication (client and server)

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.