Linux下TCP网络编程流程

常见的两种模型:C/S模型:(客户端/服务器端)和ptp(点对点)模型。

下面为TCP网络流程编程两台主机之间数据传送的具体代码示例。
代码示例:
文件server.c

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>

void main()
{
    //创建socket
    int sock=socket(PF_INET,SOCK_STREAM,0);//第一个参数告诉系统使用哪个底层协议族,对于tcp协议来说,一般设置为PF—INET表示IPv4,PF—INET6表示IPv6;第二个参数表示服务类型为流服务,第三个参数表示默认协议,一般为0;
    assert(sock!=-1);

    struct sockaddr_in ser,cli;//ser服务端,cli客户端
    memset(&ser,0,sizeof(&ser));
    ser.sin_family= AF_INET;//地址族
    ser.sin_port=htons(6500);//端口号(用户向网络,以short类型)
    ser.sin_addr.s_addr=inet_addr("127.0.0.1");//IP地址

    //绑定socket
    int res=bind(sock,(struct sockaddr*)&ser,sizeof(ser));
    assert(res!=-1);

    //监听socket
    listen(sock,5);

    while(1)
    {
        int len=sizeof(cli);
        //接收连接
        int c=accept(sock,(struct sockaddr*)&cli,&len);
        assert(c!=-1);
        printf("one client link\n");

        //接收数据
        while(1)
        {
            char buff[128]={0};
            int n=recv(c,buff,127,0);
            if(n<=0)
            {
                printf("client link break\n");
                break;
            }
            printf("buff:%s,n=%d\n",buff,n);

            //发送数据
            send(c,"OK",2,0);//第二个和第三个参数分别指写缓冲区位置和大小
        }
        close(c);
    }

    //关闭
    close(sock);

}

文件cli.c

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
void main()
{
    //创建socket
    int sock=socket(PF_INET,SOCK_STREAM,0);//第一个参数告诉系统使用哪个底层协议族,对于tcp协议来说,一般设置为PF—INET表示IPv4,PF—INET6表示IPv6;第二个参数表示服务类型为流服务,第三个参数表示默认协议,一般为0;
    assert(sock!=-1);

    struct sockaddr_in ser,cli;//ser服务端,cli客户端
    ser.sin_family = AF_INET;//地址族
    ser.sin_port=htons(6500);//端口号(用户向网络,以short类型)
    ser.sin_addr.s_addr=inet_addr("127.0.0.1");//IP地址

    //发起socket
    int res= connect(sock,(struct sockaddr*)&ser,sizeof(ser));//第二个参数指定链接的是服务器上哪个进程
    assert(res!=-1);

    while(1)
    {
        printf("please input: "),fflush(stdout);

        char buff[128]={0};
        fgets(buff,128,stdin);
        buff[strlen(buff)-1]=0;

        if(strncmp(buff,"end",3)==0)
        {
            break;
        }

    //发送数据
    send(sock,buff,strlen(buff),0);
    memset(buff,0,128);//清空
    //接收数据
    recv(sock,buff,127,0);

    printf("%s\n",buff);
    }
    //关闭
    close(sock);

}
打印结果:
编译gcc -o server server.c成功
再执行./server成功;
再打开一个终端,
编译gcc -o client client.c成功
再执行./client;
执行结果如下:
在client端口:
please input:hello
OK
please input:word
OK
please input:end
执行完,退出。
在server端口:
one client link
buff:hello,n=5
buff:word,n=4
client link break
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值