服务端
服务端代码
// server1.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/types.h>
#include <assert.h>
#include <string.h>
int main()
{
unlink("socket_server");
int server_sockfd = socket(PF_LOCAL, SOCK_STREAM, 0);
assert(server_sockfd != -1);
struct sockaddr_un address;
address.sun_family = PF_LOCAL;
address.sun_len = sizeof(address);
strcpy(address.sun_path, "socket_server");
int ret = bind(server_sockfd, (struct sockaddr *)&address, sizeof(address));
assert(ret == 0);
ret = listen(server_sockfd, 5);
assert(ret == 0);
struct sockaddr_un client_address;
int len = sizeof(client_address);
printf("accpet before...\n");
int client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &len);
assert(client_sockfd != -1);
printf("accpet ok ...\n");
char ch;
ssize_t chars_read = read(client_sockfd, &ch, 1);
assert(chars_read == 1);
ch++;
ssize_t chars_write = write(client_sockfd, &ch, 1);
assert(chars_write == 1);
close(client_sockfd);
close(server_sockfd);
return 0;
}
客户端
示例代码如下
// client1.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
int main()
{
int client_sockfd = socket(PF_LOCAL, SOCK_STREAM, 0);
assert(client_sockfd != -1);
struct sockaddr_un address;
address.sun_family = PF_LOCAL;
address.sun_len = sizeof(address);
strcpy(address.sun_path, "socket_server");
int ret = connect(client_sockfd, (struct sockaddr *)&address, sizeof(address));
if (ret == -1)
{
perror("connect");
}
assert(ret == 0);
char ch = 'A';
ssize_t chars_write = write(client_sockfd, &ch, 1);
assert(chars_write == 1);
ssize_t chars_read = read(client_sockfd, &ch, 1);
assert(chars_read == 1 && ch == 'B');
printf("ch = %c\n", ch);
close(client_sockfd);
return 0;
}
先运行server,然后运行client, client发送一个字符‘A’,server接收到‘A’,回复一个字符’B‘,client接收到’B‘