• 一个linux下socket编程的例子,client连server


    关于socket编程,以下文章写得比较好:http://www.cnblogs.com/xudong-bupt/archive/2013/12/29/3483059.html

    1. accept()函数,如果客户端一直没有连接,则服务端阻塞在accept()函数处。

    以下是client代码

    //============================================================================
    // Name        : client.cpp
    // Author      : yjzhuang
    // Version     :
    // Copyright   : yjzhuang@corp.netease.com
    // 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/in.h>  
    #include <arpa/inet.h>
    #include <string>
    #include <string.h>
    using namespace std;
    
    #define SERVER_IP "127.0.0.1"
    #define SERVER_PORT 9090
    #define BUFSIZE 1024
    
    int getSocket(){
        int fd =socket( AF_INET, SOCK_STREAM, 0 );
        cout<<"fd="<<fd<<endl;
        if(-1 == fd){
            cout<<"Error, fd is -1"<<endl;
        }
        return fd;
    }
    
    /**
     * 连接到server端,如果成功,返回fd,如果失败返回-1
     */
    int connectServer(){
        int fd = getSocket();
        cout<<"fd= "<<fd<<endl;
        if(-1 == fd){
            cout<<"Error, connectServer() quit"<<endl;
            return -1;
        }
        struct sockaddr_in remote_addr; //服务器端网络地址结构体
        memset(&remote_addr,0,sizeof(remote_addr)); //数据初始化--清零
        remote_addr.sin_family=AF_INET; //设置为IP通信
        remote_addr.sin_addr.s_addr=inet_addr(SERVER_IP);//服务器IP地址
        remote_addr.sin_port=htons(SERVER_PORT); //服务器端口号
        int con_result = connect(fd, (struct sockaddr*) &remote_addr, sizeof(struct sockaddr));
        if(con_result < 0){
            cout<<"Connect Error!"<<endl;
            return -1;
        }
        cout<<"con_result="<<con_result<<endl;
        return fd;
    }
    
    /**
    *** 连接到server端,并且不断往server端发送心跳数据
    */
    void* heartBeat(void* arg){
        cout<<"Heart bead started!"<<endl;
        int fd = connectServer();
        if(fd<0){
            cout<<"Heart bead quit!"<<endl;
            return 0;
        }
        char buf[BUFSIZE];  //数据传送的缓冲区
        string value = "This is heart beat msg!";
        strcpy(buf, value.c_str());    
        while(true){
            cout<<"to write data"<<endl;
            cout<<"buf="<<buf<<", len="<<strlen(buf)<<endl;
            int write_num = write(fd, buf, strlen(buf));
            cout<<"write_num="<<write_num<<endl;
            sleep(2);
        }
        cout<<"Heart bead finished!"<<endl;
        return 0;
    }
    
    /**
    *** 创建一个新线程,在新线程里调用heartBeat()函数
    */
    void threadCall(){
        pthread_t thread;
        pthread_create(&thread,NULL,heartBeat,NULL);
        pthread_detach(thread);
    }
    int main() {
        cout << "main started" << endl; // prints Hello World!!!
        threadCall();
    sleep(10000000);
        cout<<"main finished"<<endl;
        return 0;
    }

    以下是server代码

    /*
     * server.cpp
     *
     *  Created on: 2014年11月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/in.h>
    #include <arpa/inet.h>
    #include <string>
    #include <string.h>
    using namespace std;
    
    #define SERVER_IP "127.0.0.1"
    #define SERVER_PORT 9090
    #define BUFSIZE 1024
    
    int getSocket(){
        int fd =socket( AF_INET, SOCK_STREAM, 0 );
        if(-1 == fd){
            cout<<"Error, fd is -1"<<endl;
        }
        return fd;
    }
    
    int main(){
        int fd = getSocket();
        if(fd<0){
            cout<<"Error in main(), fd<0"<<endl;
        }
        cout<<"fd="<<fd<<endl;
        //----为服务器主线程绑定ip和port------------------------------
        struct sockaddr_in local_addr; //服务器端网络地址结构体
        memset(&local_addr,0,sizeof(local_addr)); //数据初始化--清零
        local_addr.sin_family=AF_INET; //设置为IP通信
        local_addr.sin_addr.s_addr=inet_addr(SERVER_IP);//服务器IP地址
        local_addr.sin_port=htons(SERVER_PORT); //服务器端口号
        int bind_result = bind(fd, (struct sockaddr*) &local_addr, sizeof(struct sockaddr));
        if(bind_result < 0){
            cout<<"Bind Error in main()"<<endl;
            return -1;
        }
        cout<<"bind_result="<<bind_result<<endl;
        //---------------------------------------------
        listen(fd, 10);
        struct sockaddr_in remote_addr;
        int sin_size=sizeof(struct sockaddr_in);
        cout<<"before accept"<<endl;
        int new_fd = accept(fd,  (struct sockaddr*) &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;
        char buffer[BUFSIZE];
        while(true){
            cout<<"wait to read data..."<<endl;
            int len = 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(10);
        }
    }
  • 相关阅读:
    解决PLSQL Developer中文横着显示的问题
    品优购_day06
    品优购_day05
    品优购_day04
    品优购_day03
    品优购_day02
    java 学习中遇到的问题(二)泛型中<? extends T>和<? super T>的区别
    java 学习中遇到的问题(一)方法调用中的值传递和引用传递
    java中的字符串比较
    自学java 第十一章持有对象
  • 原文地址:https://www.cnblogs.com/james6176/p/4275765.html
Copyright © 2020-2023  润新知