Linux_socket编程入门(C++)

Linux_socket编程入门(C++)

参考资料

参考:这里,还有这里

实现思路

Socket编程主要分为两部分,Server端以及Client端,以下依次从这两方面开始讲解。

Server端

需要完成的任务

  • 创建嵌套字( socket() )
  • 绑定嵌套字到IP地址以及端口上( bind() )
  • 将嵌套字设置到监听模式监听请求( listen() )
  • 请求到来后,接受请求,返回一个新的连接嵌套字( accept() )
  • 进行通信( send()/recv() )
  • 关闭嵌套字( close() )

所用到的一些函数以及结构

  • socketaddr_in:
    • sin_family (地址簇)
    • sin_port(端口)
    • sin_addr(地址)
  • socket( domain, type, protocol):返回值为-1时连接失败
    • domain (协议簇)
    • type (数据传输类型)
    • protocol (协议类型)
  • bind( sockfd, addr, addrlen)
    • sockfd (嵌套字)
    • addr (将地址赋值给嵌套字)
    • addrlen (addr所指向结构体的字节长度)
  • listen( sock, backlog)
    • sock ( 监听状态的嵌套字 )
    • backlog ( 请求队列的最大长度 )
  • accept( sock, sockaddr, addrlen):接受客户端请求
  • send( sock, buf, len, flag )
    • sock(嵌套字)
    • buf(所要发送数据,缓冲区大小)
    • len(所要发送数据字节数)
    • flags(发送数据时的选项)
  • recv():类似于send()

Client端

需要完成的任务

  • 创建嵌套字( socket() )
  • 向服务器发送连接请求( connect() )
  • 和服务器进行通信( send()/recv() )
  • 关闭嵌套字( close() )

所用到的一些函数以及结构

  • connec( sockfd, addr, addrlen):返回值为-1时连接失败

源代码

server.cpp

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int main()
{
    int client, server;
    int portNum = 1500;
    bool isExit = false;
    int bufsize = 1024;
    char buffer[bufsize];
    
    struct sockaddr_in server_addr; 
    socklen_t size;
    
    //init socket.
    
    client = socket(AF_INET, SOCK_STREAM, 0); //AF_INET指明使用TCP/IP协议簇
                                              //SOCK_STREAM指明使用流式嵌套字
                                              //使用default 协议类型 
    
    if (client < 0) //返回值为-1,连接失败 
    {
        cout<<"=> Error establishing connection."< Socket server has been created."< Error binding socket..."< Looking for client"< Error on accepting..."< 0)
    {
        strcpy(buffer,"Server connected...\n");
        send(server, buffer, bufsize, 0);
        cout<<"=> Connected with client..."< Enter # to end the connection\n"<> buffer;
                send(server, buffer, bufsize, 0);
                if(*buffer == '#')
                {
                    send(server, buffer, bufsize, 0);
                    *buffer = '*';
                    isExit = true;
                }
            }while (*buffer != '*');
            
            cout<<"Client: ";
            do{
                recv(server, buffer, bufsize, 0);
                cout << buffer <<" ";
                if(*buffer == '#')
                {
                    *buffer == '*';
                    isExit = true;
                }
            }while(*buffer != '*');
        }while(!isExit);
        
        cout<<"\n\n=> Connection terminated..."<< endl;
        cout<<"=> Goodbye..." << endl;
        isExit = false;
        exit(1);
    }
    close(client);
    return 0;   
}

client.cpp

/*
    Note the server doesn't need to know the clients port number
    but the client needs to the servers port number
*/

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int main()
{
    int client, server;
    int portNum = 1500; // note the server and clients Ip are the same
    bool isExit = false;
    int bufsize = 1024;
    char buffer[bufsize];
//  char *ip = "127.0.0.1";
    
    struct sockaddr_in server_addr;
    
    //init socket
    
    client = socket(AF_INET, SOCK_STREAM, 0);
    
    if (client < 0)
    {
        cout<<"\n=> Error creating socket."< Socket client has been created" < Connecting to server..."<< endl;
    }
    
    recv(client, buffer, bufsize, 0);
    cout<< "=> Connection confirmed" << endl;
    
    cout<< "\n=> Enter # to end the connection\n" << endl;
    
    do{
        cout<<"Client: ";
        do{
            cin >> buffer;
            send(client, buffer, bufsize, 0);
            if(*buffer == '#')
            {
                send(client, buffer, bufsize, 0);
                *buffer = '*';
                isExit = true;
            }
        } while(*buffer != 42);
        
        cout<<"Server: ";
        
        do{
            recv(client, buffer, bufsize, 0);
            cout << buffer << " ";
            if(*buffer == '#')
            {
                *buffer = '*';
                isExit = true;
            }
        }while(*buffer != 42);
        
        cout<

你可能感兴趣的:(Linux_socket编程入门(C++))