UNIX Domain Socket實現簡易聊天

*妖狐藏馬”發表於2020-10-01

UNIX Domain Socket實現簡易聊天

server.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <errno.h>
#include <stddef.h>
#include <unistd.h>
#include <pthread.h>
#define MAX_CONNECT_NUM 2
#define BUFFER_SIZE 1024
const char *filename="uds-tmp";
void *Recv(void *p)
{
	int newfd = *(int *)p;
	char buf[BUFFER_SIZE];
	while(1)
	{
		if(recv(newfd, buf, BUFFER_SIZE, 0) <= 0)
		{
			close(newfd); break;
		}
		printf("C: %s\n", buf);
		bzero(buf,sizeof(buf));
	}
}
int main()
{
	int fd,new_fd,len,i;
	struct sockaddr_un un;
	pthread_t tid;
	char buf[BUFFER_SIZE];
	fd = socket(AF_UNIX,SOCK_STREAM,0);
	if(fd < 0){
		printf("Request socket failed!\n");
		return -1;
	}
	un.sun_family = AF_UNIX;
	unlink(filename);
	strcpy(un.sun_path,filename);
	if(bind(fd,(struct sockaddr *)&un,sizeof(un)) <0 ){
		printf("bind failed!\n");
		return -1;
	}
	if(listen(fd,MAX_CONNECT_NUM) < 0){
		printf("listen failed!\n");
		return -1;
	}
	new_fd = accept(fd,NULL,NULL);
	//int ret = recv(new_fd,buffer,BUFFER_SIZE,0);
	pthread_create(&tid, NULL,Recv,&new_fd);    // 建立執行緒  執行緒接收資料資訊
	while(1)
	{
		scanf("%s",buf);
		if( send(new_fd, buf, strlen(buf), 0) < 0)
		{
			break;
		}
		bzero(buf,sizeof(buf));
	}
	close(new_fd);
	close(fd);
	return 0;
}

client.c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<sys/un.h>
#include<errno.h>
#include<stddef.h>
#include<unistd.h>
#define BUFFER_SIZE 1024
const char *filename="uds-tmp";

void *Recv(void *p)
{
	int sockfd = *(int *)p;
	char buf[BUFFER_SIZE] = {0};
	while(1)
	{
		if(recv(sockfd, buf,20,0)<=0)
		{
			break;
		}
		printf("S:%s\n", buf);
		bzero(buf,sizeof(buf));
	}
}

int main()
{
	struct sockaddr_un un;
	int sock_fd;
	char buf[BUFFER_SIZE] = {0};
	pthread_t tid;
	un.sun_family = AF_UNIX;
	strcpy(un.sun_path,filename);
	sock_fd = socket(AF_UNIX,SOCK_STREAM,0);
	if(sock_fd < 0){
		printf("Request socket failed\n");
		return -1;
	}
	if(connect(sock_fd,(struct sockaddr *)&un,sizeof(un)) < 0){
		printf("connect socket failed\n");
		return -1;
	}
	pthread_create(&tid,NULL,Recv,&sock_fd);
	while(1)
	{
		scanf("%s",buf);
		send(sock_fd, buf, strlen(buf), 0);
	}
	return 0;
}

效果截圖
在這裡插入圖片描述

相關文章