zoukankan      html  css  js  c++  java
  • [第一版]最简单的发送与接收

    server

    最大连接数为10,监听13号端口,当有客户端连接上来时,打印客户端的相关信息,同时向客户端发送当前服务器时间

    #include "unp.h"
    #include <time.h>
     
    int main(int argc, char *argv[]){
        int listenfd,connfd;
        socklen_t len;
        struct sockaddr_in servaddr,cliaddr;
        char buff[MAXLINE];
        time_t ticks;
     
        listenfd=Socket(AF_INET,SOCK_STREAM,0);
     
        bzero(&servaddr,sizeof(servaddr));
        servaddr.sin_family=AF_INET;
        servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
        servaddr.sin_port=htons(13);
     
        Bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
     
        Listen(listenfd,10);
     
        for(;;){
            len=sizeof(cliaddr);
            connfd=Accept(listenfd,(struct sockaddr *)&cliaddr,&len);
            printf("connection from %s, port %d
    ",
                    inet_ntop(AF_INET,&cliaddr.sin_addr,buff,sizeof(buff)),
                    ntohs(cliaddr.sin_port));
            ticks=time(NULL);
            snprintf(buff,sizeof(buff),"%.24s
    ",ctime(&ticks));
            write(connfd,buff,strlen(buff));
     
            Close(connfd);
        }
    }
    

    client

    连接到服务端,连接完成后只接受不发送信息,收到第一条信息后打印并退出

    #include "unp.h"
     
    int main(int argc,char *argv[]){
        int sockfd;
        struct sockaddr_in servaddr;
     
        if(argc != 2)
            err_quit("usage: client <ip address>");
     
        sockfd=Socket(AF_INET,SOCK_STREAM,0);
     
        bzero(&servaddr,sizeof(servaddr));
        servaddr.sin_family=AF_INET;
        servaddr.sin_port=htons(13);
        inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
     
        Connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
     
        char buff[1024]={0};
        read(sockfd,buff,1024);
        printf("received: %s",buff);
        exit(0);
    }
    
  • 相关阅读:
    Image Perimeters(图像周长)
    Power Strings(字符串的n次方)
    滑雪
    剪花布条
    SOJ题目分类
    Catch That Cow(捉住那头牛)
    Seek the Name, Seek the Fame(找名字,要成名)
    Avoid The Lakes(躲开湖水区)
    hash相关理论
    JAVASCRIPT共通関数数値チェック
  • 原文地址:https://www.cnblogs.com/cfans1993/p/5883370.html
Copyright © 2011-2022 走看看