c socket

Socket (Socket) is an abstraction layer, the application can send or receive data through it, it can be the same as file open, close, and write operations.

1. socke classification

  • 1.1 Stream Sockets
    it provides a reliable, bidirectional data transmission connection-oriented services, achieve error-free data, duplicate-free transmission. In the TCP / IP protocol suite, to realize the transmission of a byte stream using the TCP protocol.
  • 1.2 datagram socket
    it provides a connectionless, reliable two-way data transmission services. Packets are sent in a separate form, and retains a record boundaries, does not provide reliable guarantee. In the TCP / IP protocol suite to achieve datagram sockets use UDP protocol.
  • 1.3 raw socket
    The socket allows for lower layer protocol (such as IP or ICMP) direct access.

2. Basic Operation Function

  • Create socket socket ()
    socket () function call format:
    socket(int af,int type,int protocol);
    parameter af protocol family use the specified socket
    type parameter to specify the type of communication required. Comprising a data stream , datagram , primitive type .
    Parameter Description protocol socket protocol family used in the particular protocol. If the caller does not want to use the specified protocol is set to 0, the default connection mode.
  • bind (): bind local address
    after a socket with socket () to create, in fact, it has not been associated with any particular local or destination address
  • connect (): Connects the socket to the destination address of the
    socket is initially created is not associated with any foreign destination address. The client can call connect () binds a permanent destination address for the socket, place it in a connected state.
  • listen (): set the wait connect state
    program to a server program, when applying to the socket, and call bind () bound to a local address, you should wait for a client to request connection. listen () is the function of a socket is set to such a state.
  • accept (): accept connection requests
    server process using the system call socket, bind and listen to create a socket, bind it to a well-known port, and specify the length of the queue connection requests. Then, the server calls accept enters a wait state until it reaches a connection request.
  • send () / recv () and a sendto () / recvfrom ()
    for transmitting and receiving data.

3. c implemented network chat program]

  • client encoding process
# 
    #pragma comment(lib,"ws2_32.lib")
    #include<Winsock2.h>
    #include <stdio.h>
    #include <stdlib.h> 
    #define DATA_BUFFER 1024
    int main(int argc, char * argv[]){
    WSADATA wsaData;
    SOCKET sClient;
    int i =5;
    int iSend;
    int iPort = 5050;
    int iLen;
    char buf[DATA_BUFFER]; 
    struct sockaddr_in ser; 

    if(argc<2) 
        {
        printf("Usage: client [server IP address]\n"); 
        return -1;
        }
    memset(buf,0,sizeof(buf)); 
    if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
        {
        printf("Failed to load Winsock.\n"); 
        return -1;
        }

    ser.sin_family = AF_INET; 
    ser.sin_port = htons(iPort); 
    ser.sin_addr.s_addr = inet_addr(argv[1]);
    sClient = socket(AF_INET,SOCK_STREAM,0); 
    if(sClient == INVALID_SOCKET)
        {
        printf("socket() Failed: %d\n",WSAGetLastError());
        return -1;
        }

    if(connect(sClient,(struct sockaddr *)&ser,sizeof(ser)) == INVALID_SOCKET)
        {
        printf("connect() Failed: %d\n",WSAGetLastError());
        return -1;
        }
    else
        {
        while(i-->0)
        {   
            iLen = recv(sClient,buf,sizeof(buf),0); 
        if(iLen == 0)
            return -1;
        else if(iLen == SOCKET_ERROR)
            {
            printf("recv() Failed: %d\n",WSAGetLastError());
            return -1;
            }

            else
            printf("recv() data from server: %s\n",buf); // 输出接收数据
            printf("输入:");
            scanf("%s",buf); 
            iSend = send(sClient,buf,sizeof(buf),0); 

            if(iSend == SOCKET_ERROR) //错误处理
            {
            printf("send() Failed: %d\n",WSAGetLastError());
            break;
            }
        else if(iSend == 0)
                {
                break;
                }
            else
                {
                printf("send() byte: %d\n",iSend); //输出发送成功字节数
                }
        }
        }   
    closesocket(sClient); //关闭 socket
    WSACleanup();
    return 0;}
  • sever coding process

    #include <Winsock2.h>
    #include <stdio.h>
    #include <stdlib.h>
    #define DEFAULT_PORT 5050 //服务端默认端口
    int main(){
    int iPort = DEFAULT_PORT;  //输入端口号
    WSADATA wsaData;  //数据结构,用来存储被 WSAStartup()调用返回的socket 
    
    SOCKET sListen,sAccept;    // 
    int i =5;
    int iLen; //客户机地址长度
    int iSend; //发送数据长度
    char buf[] = "I am a server"; //要发送给客户的信息
    
    struct sockaddr_in ser,cli; //服务器和客户的地址
    
    if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
        {   
        printf("Failed to load Winsock.\n"); //Winsock 初始化错误
        return -1;
        }
        
    sListen = socket(AF_INET,SOCK_STREAM,0); //创建服务器端套接字 ,SOCK_STREAM面向连接 
    
    if(sListen == INVALID_SOCKET)         // INVALID_SOCKET= -1 
        {
        printf("socket() Failed: %d\n",WSAGetLastError()); //返回上次发生的网络错误  ,INVALID_SOCKET =-1
        return -1;
        }
    
    //以下初始化服务器端地址
    ser.sin_family = AF_INET; //使用 IP 地址族
    ser.sin_port = htons(iPort); //主机序端口号转换为网络字节序端口号
    ser.sin_addr.s_addr = htonl(INADDR_ANY); //主机序 IP 地址转换为网络字节序主机地址 INADDR_ANY :0x00000000
    
    //使用系统指定的 IP 地址 INADDR_ANY
    if(bind(sListen,(LPSOCKADDR)&ser,sizeof(ser)) == SOCKET_ERROR) //套接定与地址的绑定
        {
        printf("bind() Failed: %d\n",WSAGetLastError());
        return -1;
        }

    if(listen(sListen,5) == SOCKET_ERROR) //进入监听状态,listen的第二个参数为可以排队的最大连接个数   SOCKET_ERROR =-1 
        {
        printf("lisiten() Failed: %d\n",WSAGetLastError());
        return -1;
        } 
    iLen = sizeof(cli); //初始化客户端地址长度参数  16B
    
    while(1) //进入循环等待客户的连接请求
        {
        sAccept = accept(sListen,(struct sockaddr *)&cli,&iLen); //第一个参数:服务器的socket描述字,2: 指针,用于返回客户端的协议地址,3:协议地址的长度 
        
        if(sAccept == INVALID_SOCKET)
            {
            printf("accept() Failed: %d\n",WSAGetLastError());
            return -1;
            }
        
        printf("Accepted client IP:[%s],port:[%d]\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
        //输出客户端 IP 地址和端口号
        while(i-->0)
        {
        
        iSend = send(sAccept,buf,sizeof(buf),0); //1指定发送端套接字描述符2存放应用程序要发送数据的缓冲区3发送的数据的字节数 4一般置0 
        if(iSend == SOCKET_ERROR) //错误处理
            {
            printf("send() Failed: %d\n",WSAGetLastError());
            break;
            }
        else if(iSend == 0)
                {
                break;
                }
            else
                {
                printf("send() byte: %d\n",iSend); //输出发送成功字节数
                }
        
        iLen = recv(sAccept,buf,sizeof(buf),0); 
        if(iLen == 0)
            return -1;
        else if(iLen == SOCKET_ERROR)
            {
            printf("recv() Failed: %d\n",WSAGetLastError());
            return -1;
            }
            else
            printf("recv() data from server: %s\n",buf); // 输出接收数据

        printf("输入:");
        scanf("%s",buf); 
        }
        closesocket(sAccept);
        }
    closesocket(sListen); //关闭 socket
    WSACleanup(); //输出发送成功字节数
    return 0;}
  • Output

    Client

Service-Terminal

Guess you like

Origin www.cnblogs.com/lhx9527/p/11994638.html