代码:
server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/un.h>
int main()
{
//创建socket文件
int sockfd = socket(AF_UNIX,SOCK_STREAM,0);
if(0 > sockfd)
{
perror("socket");
return EXIT_FAILURE;
}
//准备通信地址
struct sockaddr_un addr = {};
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path,"sock");
socklen_t addrlen = sizeof(addr);
//绑定
if(bind(sockfd,(struct sockaddr*)&addr,addrlen))
{
perror("bind");
return EXIT_FAILURE;
}
//监听
if(listen(sockfd,5))
{
perror("listen");
return EXIT_FAILURE;
}
//等待连接
int con_fd = accept(sockfd,(struct sockaddr*)&addr,&addrlen);
if(0 > con_fd)
{
perror("accept");
return EXIT_FAILURE;
}
printf("有人连接成功!\n");
char buf[4096] = {};
size_t buf_size = sizeof(buf);
for(;;)
{
printf("recv:");
fflush(stdout);
//接收数据
read(con_fd,buf,buf_size);
if(0 == strcmp(buf,"quit"))
{
printf("通信结束!\n");
break;
}
printf("%s\n",buf);
//发送数据
printf(">>>");
scanf("%s",buf);
write(con_fd,buf,strlen(buf)+1);
if(0 == strcmp(buf,"quit"))
{
printf("通行结束!\n");
break;
}
}
//关闭socket
close(con_fd);
close(sockfd);
//删除文件
unlink(addr.sun_path);
}
client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/un.h>
int main()
{
//创建socket文件
int sockfd = socket(AF_UNIX,SOCK_STREAM,0);
if(0 > sockfd)
{
perror("socket");
return EXIT_FAILURE;
}
//准备通信地址
struct sockaddr_un addr = {};
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path,"sock");
socklen_t addrlen = sizeof(addr);
//连接
if(connect(sockfd,(struct sockaddr*)&addr,addrlen))
{
perror("connect");
return EXIT_FAILURE;
}
char buf[4096] = {};
size_t buf_size = sizeof(buf);
for(;;)
{
//发送数据
printf(">>>");
scanf("%s",buf);
write(sockfd,buf,strlen(buf)+1);
if(0 == strcmp(buf,"quit"))
{
printf("通行结束!\n");
break;
}
printf("recv:");
fflush(stdout);
//接收数据
read(sockfd,buf,buf_size);
if(0 == strcmp(buf,"quit"))
{
printf("通信结束!\n");
break;
}
printf("%s\n",buf);
}
//关闭socket
close(sockfd);
}
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_CFLAGS := -Wall -Werror
LOCAL_CLANG := true
LOCAL_MODULE := server
LOCAL_SHARED_LIBRARIES := libcutils
LOCAL_SRC_FILES := server.c
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_CFLAGS := -Wall -Werror
LOCAL_CLANG := true
LOCAL_MODULE := client
LOCAL_SHARED_LIBRARIES := libcutils
LOCAL_SRC_FILES := client.c
include $(BUILD_EXECUTABLE)
结束。经常用到的一个小工具。