A Linux socket Programming example, the Client connection server

Source: Internet
Author: User
Tags socket error server port htons

With regard to socket programming, the following articles are well written: http://www.cnblogs.com/xudong-bupt/archive/2013/12/29/3483059.html

1. The Accept () function, if the client has not been connected, the server is blocked at the Accept () function.

The following is the client code

//============================================================================//Name:client.cpp//Author:yjzhuang//Version://Copyright: [email protected]//Description:hello World in C + +, Ansi-style//============================================================================#include<iostream>#include<sys/Select.h>#include<sys/socket.h>#include<unistd.h>#include<pthread.h>#include<stdio.h>#include<sys/types.h>#include<netinet/inch.h>#include<arpa/inet.h>#include<string>#include<string.h>using namespacestd;#defineServer_ip "127.0.0.1"#defineServer_port 9090#defineBUFSIZE 1024intGetsocket () {intFD =socket (af_inet, Sock_stream,0 ); cout<<"fd="<<fd<<Endl; if(-1==FD) {cout<<"Error, FD is-1"<<Endl; }    returnFD;}/** * Connect to server side, if successful, return FD if failed returns-1*/intConnectServer () {intFD =Getsocket (); cout<<"fd="<<fd<<Endl; if(-1==FD) {cout<<"Error, ConnectServer () quit"<<Endl; return-1; }    structSockaddr_in remote_addr;//server-side network address structurememset (&AMP;REMOTE_ADDR,0,sizeof(REMOTE_ADDR));//data Initialization--clear 0Remote_addr.sin_family=af_inet;//set to IP communicationREMOTE_ADDR.SIN_ADDR.S_ADDR=INET_ADDR (SERVER_IP);//Server IP AddressRemote_addr.sin_port=htons (Server_port);//Server port number    intCon_result = Connect (FD, (structsockaddr*) &remote_addr,sizeof(structsockaddr)); if(Con_result <0) {cout<<"Connect error!"<<Endl; return-1; } cout<<"con_result="<<con_result<<Endl; returnFD;}/** * * * Connect to server side and continue to send heartbeat data to server side*/void* HeartBeat (void*Arg) {cout<<"Heart Bead started!"<<Endl; intFD =ConnectServer (); if(fd<0) {cout<<"Heart Bead quit!"<<Endl; return 0; }    CharBuf[bufsize];//buffer for data transfer    stringValue ="This is heart beat msg!";        strcpy (buf, Value.c_str ());  while(true) {cout<<"To write Data"<<Endl; cout<<"buf="<<buf<<", len="<<strlen (BUF) <<Endl; intWrite_num =Write (FD, buf, strlen (BUF)); cout<<"write_num="<<write_num<<Endl; Sleep (2); } cout<<"Heart Bead finished!"<<Endl; return 0;}/** * * Create a new thread and call the heartbeat () function in a new thread*/voidThreadcall () {pthread_t thread; Pthread_create (&thread,null,heartbeat,null); Pthread_detach (thread);}intMain () {cout<<"Main started"<< Endl;//prints Hello World!!!Threadcall (); Sleep (10000000); cout<<"Main finished"<<Endl; return 0;}

The following is the server code

/** server.cpp * * Created on:2014 November 14 * Author:yjzhuang*/#include<iostream>#include<sys/Select.h>#include<sys/socket.h>#include<stdio.h>#include<unistd.h>#include<pthread.h>#include<stdio.h>#include<sys/types.h>#include<netinet/inch.h>#include<arpa/inet.h>#include<string>#include<string.h>using namespacestd;#defineServer_ip "127.0.0.1"#defineServer_port 9090#defineBUFSIZE 1024intGetsocket () {intFD =socket (af_inet, Sock_stream,0 ); if(-1==FD) {cout<<"Error, FD is-1"<<Endl; }    returnFD;}intMain () {intFD =Getsocket (); if(fd<0) {cout<<"Error in Main (), fd<0"<<Endl; } cout<<"fd="<<fd<<Endl; //----Bind the IP and port to the server main thread------------------------------    structSockaddr_in local_addr;//server-side network address structurememset (&AMP;LOCAL_ADDR,0,sizeof(LOCAL_ADDR));//data Initialization--clear 0Local_addr.sin_family=af_inet;//set to IP communicationLOCAL_ADDR.SIN_ADDR.S_ADDR=INET_ADDR (SERVER_IP);//Server IP AddressLocal_addr.sin_port=htons (Server_port);//Server port number    intBind_result = Bind (FD, (structsockaddr*) &local_addr,sizeof(structsockaddr)); if(Bind_result <0) {cout<<"Bind Error in main ()"<<Endl; return-1; } cout<<"bind_result="<<bind_result<<Endl; //---------------------------------------------Listen (FD,Ten); structsockaddr_in remote_addr; intSin_size=sizeof(structsockaddr_in); cout<<"before accept"<<Endl; intNEW_FD = Accept (FD, (structsockaddr*) &remote_addr, (socklen_t*) &sin_size); cout<<"After accept"<<Endl; if(New_fd <0) {cout<<"Accept Error in main ()"<<Endl; return-1; } cout<<"NEW_FD accepted is"<<new_fd<<Endl; CharBuffer[bufsize];  while(true) {cout<<"wait to read data ..."<<Endl; intLen =Read (new_fd, buffer, BUFSIZE); if(len = =0) {cout<<"Read from socket finished"<<Endl; return 0; }Else if(Len <0) {cout<<"Read from socket error"<<Endl; return-1; } cout<<"Accept Data:"<<buffer<<Endl; Sleep (Ten); }}

A Linux socket Programming example, the Client connection 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.