zoukankan      html  css  js  c++  java
  • 简单的TCP接受在转发到客户端的套接口

    //功能:客服端发送tcp包,服务器接受到并打印出来,并将包转换为大写后到客户端
    //2015.9.10成功

    #include <stdio.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <netdb.h>
    int port = 8000;

    int main()
    {
    struct sockaddr_in sin,cliaddr;
    struct sockaddr_in pin;
    int sock_descriptor;
    int temp_sock_descriptor;
    int address_size;
    char buf[16384];
    int i, len;

    sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);//TCP连接
    if (sock_descriptor == -1) {
    perror("call to socket");
    exit(1);
    }

    bzero(&sin, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;//自动填入本机IP地址
    sin.sin_port = htons(port);
    if (bind(sock_descriptor, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
    perror("call to bind");
    exit(1);
    }
    if (listen(sock_descriptor, 20) == -1) {
    perror("call to listen");
    exit(1);
    }

    printf("Accepting connections ... ");
    int addr_len=sizeof(struct sockaddr_in);
    while(1)
    {

    int temp_sock_descriptor = accept(sock_descriptor, (struct sockaddr *)&pin,&address_size);
    if (temp_sock_descriptor == -1) {
    perror("call to accept");
    exit(1);
    }
    if (recv(temp_sock_descriptor, buf, 16384, 0) == -1) {
    perror("call to recv");
    exit(1);
    }

    // for this server example, we just convert the
    // characters to upper case:
    len = strlen(buf);
    for (i=0; i<len; i++) buf[i] = toupper(buf[i]);
    //toupper将字符c转换为大写英文字母
    printf("sendbuff=%s ",buf);


    // 再次 发回到客户端
    if (send(temp_sock_descriptor, buf, len, 0) == -1) {
    perror("call to send");
    exit(1);
    }
    close(temp_sock_descriptor);
    }
    }

  • 相关阅读:
    Word Search
    Subsets
    Combinations
    Search a 2D Matrix
    求比正整数N大的最小正整数M,且M与N的二进制表示中有相同数目的1
    Set Matrix Zeroes
    Unity学习笔记—— 常用脚本函数
    学习 各个数据结构
    unity调用 安卓相册
    设置 相机跟随 主角及视角 滑动
  • 原文地址:https://www.cnblogs.com/zhouhbing/p/4837224.html
Copyright © 2011-2022 走看看