第二十四次作业——TCP服务器

本文详细介绍了使用C语言通过socket编程创建一个简单的TCP服务器,包括创建流式套接字、绑定、监听和接受客户端连接,以及数据收发的过程。
摘要由CSDN通过智能技术生成

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <dochead.h>


#define PORT 6666
#define IP "192.168.124.193"

int main(int argc, const char *argv[])
{
    int sfd = socket(AF_INET,SOCK_STREAM,0); //创建流式套接字文件
    if(sfd<0)
    {   
        fprintf(stderr,"error line:%d\n",__LINE__);
        perror("sfd socket");
        return -1; 
    }   
    printf("创建流式套接字成功 line:%d\n",__LINE__);

    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(PORT);
    sin.sin_addr.s_addr = inet_addr(IP);

    int bd=bind(sfd,(struct sockaddr*)&sin,sizeof(sin));
    if(bd < 0)
    {   
        fprintf(stderr,"stderr,line:%d\n",__LINE__);
        perror("bind");
        return -1; 
    }   

    if(listen(sfd,128)<0)//设置监听
    {   
        fprintf(stdout,"listen line:%d\n",__LINE__);
        perror("listen");
        return -1; 
    }   

    struct sockaddr_in cin;
    socklen_t len=sizeof(cin);
    int newfd=accept(sfd,(struct sockaddr*)&cin,&len);
    if(newfd < 0)
    {   
        fprintf(stdout,"accept line:%d\n",__LINE__);
        perror("accept");
        return -1; 
    }   

    char buf[128];
    ssize_t res;
    while(1)
    {   
        bzero(buf,sizeof(buf));
        res=recv(newfd,buf,sizeof(buf),0);
        if(res<0)
        {
            perror("recv");
            return -1; 
        }
        else if(res == 0)
        {
            printf("客户端关闭\n");
            break;
        }
        else
        {

            printf("%s\n",buf);
        }
            printf("输入数据:\n");
            fgets(buf,sizeof(buf),stdin);
            buf[strlen(buf)-1]='\0';

            res=send(newfd,buf,sizeof(buf),0);
            if(res<0)
            {
                perror("send");
                return -1; 
            }
            //printf("%s\n",buf);                          

    }   
    close(sfd);
    close(newfd);
    return 0;
}                                                                                                                      
                                                                                                                      
 

  • 7
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值