socket套接字TCP API

时间:2014-08-01 09:15:31   收藏:0   阅读:451

socket套接字TCP API

socket概念

套接字地址结构

socket基本TCP API

connect函数

bind函数

listen函数

accept函数

close函数

传送数据

TCP通信客户端与服务器端

客户端流程

服务器端流程

源代码如下:

#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>

int main(){
    struct sockaddr_in local;
    int s;
    int sl;
    int rc;
    char buf[1000];

    local.sin_family = AF_INET;
    local.sin_port = htons(7500);
    local.sin_addr.s_addr = htonl(INADDR_ANY);
    s = socket(AF_INET, SOCK_STREAM, 0);
    if ( s < 0){
        perror("socket call failed");
        exit(1);
    }
    rc = bind(s, (struct sockaddr *) &local, sizeof(local));
    if ( rc < 0){
        perror("bind call failed");
        exit(1);
    }
    rc = listen(s, 5);
    if ( rc < 0){
        perror("listen call failed");
        exit(1);
    }
    sl = accept(s, NULL, NULL);
    if ( sl < 0){
        perror("accept call failed");
        exit(1);
    }
    rc = recv(sl, buf, 10, 0);
    if ( rc < 0){
        perror("recv call failed");
        exit(1);
    }
    printf("%s\n", buf);
    rc = send(sl, "good", 10, 0);
    if ( rc < 0){
        perror("send call failed");
        exit(1);
    }
    exit(0);
}
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>

int main(){
    struct sockaddr_in peer;
    int s;
    int rc;
    char buf[100];

    peer.sin_family = AF_INET;
    peer.sin_port = htons(7500);
    peer.sin_addr.s_addr = inet_addr("127.0.0.1");

    s = socket(AF_INET, SOCK_STREAM, 0);
    if ( s < 0 ){
        perror("socket call failed");
        exit(1);
    }
    rc = connect(s, (struct sockaddr *) &peer, sizeof(peer));
    if (rc){
        perror("connect call failed");
        exit(1);
    }
    rc = send(s, "hello", 10, 0);
    if (rc <= 0)
    {
        perror("send call failed");
        exit(1);
    }
    rc = recv(s, buf, 10, 0);
    if (rc <= 0){
        perror("recv call failed");
    }
    else
        printf("%s\n", buf);

    exit(0);
}

 
 

转载请注明作者:Focustc,博客地址为http://blog.csdn.net/caozhk,原文链接为点击打开

socket套接字TCP API,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!