网络编程 day1

TCP 基础模型

服务器端

#include
#define IP "192.168.125.83"

int main(int argc, const char *argv[])
{
    //创建套接字
    int sfd = socket(AF_INET,SOCK_STREAM,0);

    //绑定IP地址和端口号
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(8888);
    sin.sin_addr.s_addr = inet_addr(IP);
    bind(sfd,(struct sockaddr*)&sin,sizeof(sin));
    //监听允许客户端连接 
    listen(sfd,128);
    //接收客户端连接请求
    int newfd = accept(sfd,NULL,NULL);
    //跟客户端进行通信
    char buf[128] = "";
    while(1)
    {
        bzero(buf,sizeof(buf));
        read(newfd,buf,sizeof(buf));
        printf("收到客户端消息为:%s\n",buf);
    }
    //关闭服务器
    return 0;
}

用户端

#include
#define IP "192.168.125.83"

int main(int argc, const char *argv[])
{
    //创建套接字
    int cfd = socket(AF_INET,SOCK_STREAM,0);

    //绑定IP地址和端口号,连接客户端
    struct sockaddr_in cin;
    cin.sin_family = AF_INET;
    cin.sin_port = htons(8888);
    cin.sin_addr.s_addr = inet_addr(IP);
    connect(cfd,(struct sockaddr*)&cin,sizeof(cin));
    //跟服务器进行通信
    char buf[128] = "";
    while(1)
    {
        printf("请输入:");
        fgets(buf,sizeof(buf),stdin);
        buf[strlen(buf)-1] = 0;

        
        write(cfd,buf,sizeof(buf));
        printf("发送成功\n");
    }
    close(cfd);
    return 0;
}

 

你可能感兴趣的:(网络,服务器,linux)