• BSD Socket~TCP~Example Code


    TCP 协议实现 C版本号,可用于Mac OS X机器上执行

    Server: 

    /*
    Setting up a simple TCP server involves the following steps:
    
    Creating a TCP socket, with a call to socket().
    Binding the socket to the listen port, with a call to bind(). Before calling bind(), a programmer must declare a sockaddr_in structure, clear it (with memset()), and the sin_family (AF_INET), and fill its sin_port (the listening port, in network byte order) fields. Converting a short int to network byte order can be done by calling the function htons() (host to network short).
    Preparing the socket to listen for connections (making it a listening socket), with a call to listen().
    Accepting incoming connections, via a call to accept(). This blocks until an incoming connection is received, and then returns a socket descriptor for the accepted connection. The initial descriptor remains a listening descriptor, and accept() can be called again at any time with this socket, until it is closed.
    Communicating with the remote host, which can be done through send() and recv() or write() and read().
    Eventually closing each socket that was opened, once it is no longer needed, using close().
    Code may set up a TCP server on port 1100 as follows:
    */
    
    /* Server code in C */
     
      #include <sys/types.h>
      #include <sys/socket.h>
      #include <netinet/in.h>
      #include <arpa/inet.h>
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <unistd.h>
     
      int main(void)
      {
        struct sockaddr_in stSockAddr;
        int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
     
        if(-1 == SocketFD)
        {
          perror("can not create socket");
          exit(EXIT_FAILURE);
        }
     
        memset(&stSockAddr, 0, sizeof(stSockAddr));
     
        stSockAddr.sin_family = AF_INET;
        stSockAddr.sin_port = htons(1100);
        stSockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
     
        if(-1 == bind(SocketFD,(struct sockaddr *)&stSockAddr, sizeof(stSockAddr)))
        {
          perror("error bind failed");
          close(SocketFD);
          exit(EXIT_FAILURE);
        }
     
        if(-1 == listen(SocketFD, 10))
        {
          perror("error listen failed");
          close(SocketFD);
          exit(EXIT_FAILURE);
        }
     
        for(;;)
        {
          int ConnectFD = accept(SocketFD, NULL, NULL);
     
          if(0 > ConnectFD)
          {
            perror("error accept failed");
            close(SocketFD);
            exit(EXIT_FAILURE);
          }
     
          /* perform read write operations ... 
          read(ConnectFD,buff,size)*/
     
          if (-1 == shutdown(ConnectFD, SHUT_RDWR))
          {
            perror("can not shutdown socket");
            close(ConnectFD);
            close(SocketFD);
            exit(EXIT_FAILURE);
          }
          close(ConnectFD);
        }
     
        close(SocketFD);
        return EXIT_SUCCESS;  
    }



    Client

    /*
    Programming a TCP client application involves the following steps:
    
    Creating a TCP socket, with a call to socket().
    Connecting to the server with the use of connect(), passing a sockaddr_in structure with the sin_family set to AF_INET, sin_port set to the port the endpoint is listening (in network byte order), and sin_addr set to the IP address of the listening server (also in network byte order.)
    Communicating with the server by using send() and recv() or write() and read().
    Terminating the connection and cleaning up with a call to close().
    */
    
      /* Client code in C */
     
      #include <sys/types.h>
      #include <sys/socket.h>
      #include <netinet/in.h>
      #include <arpa/inet.h>
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <unistd.h>
     
      int main(void)
      {
        struct sockaddr_in stSockAddr;
        int Res;
        int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
     
        if (-1 == SocketFD)
        {
          perror("cannot create socket");
          exit(EXIT_FAILURE);
        }
     
        memset(&stSockAddr, 0, sizeof(stSockAddr));
     
        stSockAddr.sin_family = AF_INET;
        stSockAddr.sin_port = htons(1100);
        Res = inet_pton(AF_INET, "192.168.1.3", &stSockAddr.sin_addr);
     
        if (0 > Res)
        {
          perror("error: first parameter is not a valid address family");
          close(SocketFD);
          exit(EXIT_FAILURE);
        }
        else if (0 == Res)
        {
          perror("char string (second parameter does not contain valid ipaddress)");
          close(SocketFD);
          exit(EXIT_FAILURE);
        }
     
        if (-1 == connect(SocketFD, (struct sockaddr *)&stSockAddr, sizeof(stSockAddr)))
        {
          perror("connect failed");
          close(SocketFD);
          exit(EXIT_FAILURE);
        }
     
        /* perform read write operations ... */
     
        (void) shutdown(SocketFD, SHUT_RDWR);
     
        close(SocketFD);
        return EXIT_SUCCESS;
      }



    Link:

    BSD Socket  Wikipedia

  • 相关阅读:
    HashMap是无序的
    mysql随笔
    visual stdio 安装OpenGL库文件
    myeclipse解决JSP文件里script背景颜色的调整
    js的鼠标事件整理-------Day47
    Linux环境编程之IPC进程间通信(五):Posix消息队列1
    HDFS 读取、写入、遍历文件夹获取文件全路径、append
    Appfuse搭建过程(下源代码不须要maven,lib直接就在项目里(否则痛苦死!))
    CSS样式命名规则
    关于c++ list容器的操作摸索
  • 原文地址:https://www.cnblogs.com/wzjhoutai/p/6726351.html
Copyright © 2020-2023  润新知