建立 Socket 连接至少需要一对套接字,其中一个运行于客户端,称为 ClientSocket ,另一个运行于服务器端,称为 ServerSocket套接字之间的连接过程可以分为三个步骤:服务器监听,客户端请求,连接确认。
1.首先建立客户端的socket
vi client1.c
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int sockfd;
int len;
struct sockaddr_un address;
int result;
char ch = 'A';
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
address.sun_family = AF_UNIX;
strcpy(address.sun_path, "server_socket");
len = sizeof(address);
result = connect (sockfd, (struct sockaddr *)&address, len);
if(result == -1){
perror("oops:client1");
exit(1);
}
write(sockfd, &ch, 1);
read(sockfd, &ch, 1);
printf("char from server = %c\n", ch);
close(sockfd);
exit(0);
}
然后编译
gcc client1.c -o client1
运行client1
./client1
运行后会提示:
oops: client1: No such file or directy
运行的时候会失败,因为还没有创建服务器端的socket
2.接下来创建一个非常简单的服务端socket程序 server1.c
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_un server_address;
struct sockaddr_un client_address;
//用完的socket文件必须清理掉
unlink("server_socket");
server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
server_address.sun_family = AF_UNIX;
strcpy(server_address.sun_path, "server_socket");
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
listen(server_sockfd, 5);
while(1){
char ch;
printf("server waiting\n");
client_len = sizeof(client_address);
client_sockfd = accept (server_sockfd, (struct sockaddr *)&server_address, (socklen_t *)&client_len);
read(client_sockfd, &ch, 1);
ch++;
write(client_sockfd, &ch, 1);
close(client_sockfd);
}
}
编译文件后运行
gcc server1.c -o server1 & ./server1 &
[1] 2552
server waiting
这时候表明服务端的socket进程监听和等待客户端的连接,使用ps命令可以看到当前的进程正在后台运行,并且处于休眠状态,因此它没有消耗CPU资源。
ps lx | grep './server1'
0 2552 2286 0 31 0 2432748 524 - S s000 0:00.00 ./server1
0 2556 2286 0 31 0 2433772 536 - S s000 0:00.00 ./server1
0 2616 2286 0 31 0 2432748 524 - S s000 0:00.00 ./server1
0 2626 2286 0 31 0 2432748 524 - S s000 0:00.00 ./server1
3.客户端连接服务端socket
现在我们可以建立连接了,新开一个terminal窗口,使用命令:
./client1
将会响应:
char from server = B
而之前的server终端将显示
server waiting
如果同时运行多个客户,server端会依次服务
./client1 & ./client1 & ./client1 & ./client1
响应:
[1] 2641
[2] 2642
[3] 2643
char from server = B
char from server = B
char from server = B
char from server = B
[1] Done ./client1
[2]- Done ./client1
[3]+ Done ./client1
That's it~