linux系统编程之网络编程

本文介绍了如何使用C语言实现简单的socket网络编程,包括建立服务端和客户端,实现双方聊天功能。此外,还展示了如何扩展服务端以支持多客户端同时聊天,通过创建子进程来处理每个客户端的连接和通信,从而实现多人聊天室的功能。
摘要由CSDN通过智能技术生成

socket网络编程

一、实现双方聊天

1.服务端代码(server.c)

#include <stdio.h>
#include <sys/types.h>			
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
/*
    描述:实现双方聊天的程序,此为服务端
*/

/*
/*
需要用到的API
int socket(int domain, int type, int protocol);
int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
int listen(int sockfd, int backlog);
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
转网络字节序
uint16_t htons(uint16_t hostshort);
uint16_t ntohs(uint16_t netshort);
需要用到的结构体
struct sockaddr_in {
				   sa_family_t	  sin_family;		  IPV4对应AF_INET
				   u_int16_t	  sin_port; 		  端口号
				   struct in_addr sin_addr; 		  IP地址
			   };

*/

*/
int main(int argc,char**argv)
{
	
	int server_id;
    int client_id;
	struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	char read_buffer[128];
    char *msg = "Received,poorguy of message";

    if(argc != 3)
    {
        printf("invaid parameter\n");
        return -1;
    }
    //清空连接
    memset(&server_addr,0,sizeof(struct sockaddr_in));
    memset(&client_addr,0,sizeof(struct sockaddr_in));

    
    //1.创建套接字
	server_id = socket(AF_INET,SOCK_STREAM,0);
	if(server_id == -1)
	{
		printf("create socket failed\n");
		return -1;
	}

	server_addr.sin_family = AF_INET;//IPV4对应AF_INET
	server_addr.sin_port = htons(atoi(argv[2]));//设置端口号

	inet_aton(argv[1],&server_addr.sin_addr);//转换为网络能识别的格式


    //2.绑定地址
	if( bind(server_id,(struct sockaddr *)&server_addr,sizeof(struct sockaddr)) == -1 )
	{
		
		printf("bind error\n");
	}
    //3.监听客户端连接请求
	listen(server_id,10);//可监听10个客户端连接

    

	//4. C/S 数据交互
	int client_len = sizeof(struct sockaddr);
	while(1)
	{
        //等待接收客户端连接
		client_id = accept(server_id,(struct sockaddr *)&client_addr,&client_len);
		if( client_id == -1 )
		{
			printf("connect failed\n");
            
		}
		

		//打印客户端地址
		printf("get connect:%s\n",inet_ntoa(client_addr.sin_addr));
		//创建子进程对接客户端
		if(fork() == 0)
		{
            memset(read_buffer,0,sizeof(read_buffer));
			//读取客户端发来的消息
			int read_byte = read(client_id,read_buffer,128);
			if(read_byte == -1 )
			{
				printf("read message failed\n");
			}
			
			printf("From client message:%s\n",read_buffer);
            
			//回复信息给客户端
			int write_byte = write(client_id,msg,strlen(msg));
			if(write_byte==-1)
			{
                printf("send message fail\n");
			}
			break;//子进程完成一次收发操作就退出,父进程继续接收数据
		}
	}
	
	return 0;
}

2.客户端代码(client.c)

#include <stdio.h>		
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>

/*
    描述:实现双方聊天的程序,此为客户端
*/

/*
/*
需要用到的API
int socket(int domain, int type, int protocol);
int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
int listen(int sockfd, int backlog);
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
转网络字节序
uint16_t htons(uint16_t hostshort);
uint16_t ntohs(uint16_t netshort);
需要用到的结构体
struct sockaddr_in {
				   sa_family_t	  sin_family;		  IPV4对应AF_INET
				   u_int16_t	  sin_port; 		  端口号
				   struct in_addr sin_addr; 		  IP地址
			   };

*/

int main(int argc,char**argv)
{
	
	int client_id;
	//struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	char read_buffer[128];
	char msg[128];

    if(argc != 3)
    {
        printf("invaid parameter\n");
        return -1;
    }
    memset(&client_addr,0,sizeof(struct sockaddr_in));
    //1.创建套接字
	client_id = socket(AF_INET,SOCK_STREAM,0);
	if(client_id == -1)
	{
		printf("create socket failed\n");
		return -1;
	}

	client_addr.sin_family = AF_INET;//IPV4对应AF_INET
	client_addr.sin_port = htons(atoi(argv[2]));//设置端口号

	inet_aton(argv[1],&client_addr.sin_addr);//转换为网络能识别的格式

    
    //2.发送连接请求给服务端
    if ( connect(client_id,(struct sockaddr *)&client_addr,sizeof(struct sockaddr_in)) == -1 )
    {
                printf("connect fail\n");        
    }

    //3.数据交互
    printf("input data:");
    gets(msg);//linux gcc编译器不支持这个函数,会有警告
    //发送消息给服务端
    if( write(client_id,msg,strlen(msg)) == -1)
    {
              printf("send message failed\n");
     
    }
    //读取服务端   
    memset(read_buffer,0,sizeof(read_buffer));    
    if( read(client_id,read_buffer,sizeof(read_buffer)) == -1)
    {   
                printf("read message failed\n");
    }

    printf("From server message:%s\n",read_buffer);
    
    return 0;
}

3.效果截图

在这里插入图片描述

二、多客户端互相聊天

1.多人聊天服务端代码(server_pro.c)

#include <stdio.h>
#include <sys/types.h>			
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
/*
    描述:实现多方聊天的程序,此为服务端
*/
int main(int argc,char**argv)
{
	
	int server_id;
    int client_id;
	struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	char read_buffer[128];
    char *msg = "Received,poorguy of message";

    if(argc != 3)
    {
        printf("invaid parameter\n");
        return -1;
    }

    //清空连接
    memset(&server_addr,0,sizeof(struct sockaddr_in));
    memset(&client_addr,0,sizeof(struct sockaddr_in));

    //1.创建套接字
	server_id = socket(AF_INET,SOCK_STREAM,0);
	if(server_id == -1)
	{
		printf("create socket failed\n");
		return -1;
	}

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(argv[2]));

	inet_aton(argv[1],&server_addr.sin_addr);//转换为网络能识别的格式

    //2.绑定地址
	if( bind(server_id,(struct sockaddr *)&server_addr,sizeof(struct sockaddr)) == -1 )
	{
		
		printf("bind error\n");
	}
    //3.监听客户端连接请求
	listen(server_id,10);//可监听10个客户端连接

	//4. C/S 数据交互
	int client_len = sizeof(struct sockaddr);

    int count = 0;
	while(1)
	{
        
		client_id = accept(server_id,(struct sockaddr *)&client_addr,&client_len);
		if( client_id == -1 )
		{
			printf("connect failed\n");
            
		}
		
		//打印客户端地址
		printf("get connect:%s\n",inet_ntoa(client_addr.sin_addr));
        
        count++;
        
		//创建子进程对接客户端
		if(fork() == 0)
		{
			
			if(fork() == 0)
			{
                
                while(1)
                {
                    sprintf(msg,"欢迎第%d个客户端加入聊天室\n",count);
                    int write_byte = write(client_id,msg,strlen(msg));
                    sleep(5);
                }
            }
            //读取客户端发来的消息
            while(1)
            {
                memset(read_buffer,0,sizeof(read_buffer));//清空read_buffer中的数据
                int read_byte = read(client_id,read_buffer,128);
    			if(read_byte == -1 )
    			{
    				printf("read message failed\n");
    			}
    			
    			printf("From NO.%d message:%s\n",count,read_buffer);
                //客户端输入“quit”退出聊天室
                if(strcmp(read_buffer,"quit") == 0)
                {
                    printf("NO.%d client quit chatroom\n",count);
                    break;
                }    
            }           			
		}
	}
    close(server_id);
    close(client_id);
	return 0;
}

2.多人聊天客户端代码(client_pro.c)

#include <stdio.h>		
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>

/*
    描述:实现双方聊天的程序,此为客户端
*/

int main(int argc,char**argv)
{
	
	int client_id;
	struct sockaddr_in client_addr;
	char read_buffer[128];
	char msg[128];

    if(argc != 3)
    {
        printf("invaid parameter\n");
        return -1;
    }
    memset(&client_addr,0,sizeof(struct sockaddr_in));
    //1.创建套接字
	client_id = socket(AF_INET,SOCK_STREAM,0);
	if(client_id == -1)
	{
		printf("create socket failed\n");
		return -1;
	}

	client_addr.sin_family = AF_INET;
	client_addr.sin_port = htons(atoi(argv[2]));

	inet_aton(argv[1],&client_addr.sin_addr);//转换为网络能识别的格式

    
    //2.发送连接请求给服务端
    if ( connect(client_id,(struct sockaddr *)&client_addr,sizeof(struct sockaddr_in)) == -1 )
    {
                printf("connect fail\n");        
    }

    //3. C/S 数据交互
    while(1)
    {
        
        //发送消息给服务端
        if(fork() == 0)
        {      
            while(1)
            {
                printf("input data:");
                gets(msg);
                if( write(client_id,msg,strlen(msg)) == -1)
                {
                          printf("send message failed\n");
                 
                }
            }
        }
        //读取服务端消息   
        while(1)
        {
            memset(read_buffer,0,sizeof(read_buffer));//清空缓冲区数据    
            if( read(client_id,read_buffer,sizeof(read_buffer)) == -1)
            {   
                        printf("read message failed\n");
            }

            printf("From server message:%s\n",read_buffer);
        }
    }
    return 0;
}

3.多人聊天效果截图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值