70,020
社区成员




// socket-server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
// 服务端:不断从套接字读取并输出文本信息直到套接字关闭。当客户端发送"quit"消息>时返回非 0 值,否则返回 0
int server(int client_socket)
{
while(1) {
int length; /* 消息的长度 */
char* text_buf; /* 保存信息的缓冲区 */
// 获取消息长度。如果 read 返回 0 说明客户端关闭了连接
if(read(client_socket, &length, sizeof(length)) == 0)
return 0;
// 分配用于保存信息的缓冲区
text_buf = (char*) malloc(length);
// 读取并输出信息
read(client_socket, text_buf, length);
// 如果客户发送"quit"消息,结束任务
if(!strcmp(text_buf, "quit"))
{
// 释放缓冲区
free(text_buf);
return 1;
}
printf("Client says: %s\n", text_buf);
// 释放缓冲区
free(text_buf);
return 0;
}
}
int main()
{
const char* socket_name = "/tmp/socket"; /* 套接字路径名 (/path/filename) */
int socket_fd; /* 套接字文件描述符 */
struct sockaddr_un name; /* 监听套接字地址结构 */
int client_sent_quit_message; /* 布尔值:客户端是否发送了"quit"消息 */
// 创建套接字: 本地套接字,连接型
socket_fd = socket(PF_LOCAL, SOCK_STREAM, 0);
// 将服务器地址写入套接字地址结构
name.sun_family = AF_LOCAL;
strcpy(name.sun_path, socket_name);
// 绑定套接字,指明这是服务器
bind(socket_fd, (struct sockaddr*) &name, SUN_LEN(&name));
// 监听连接,最大允许尝试连接数为 5
listen(socket_fd, 5);
// 不断接受连接,循环调用 server() 处理连接。直到客户发送"quit"消息时推出
do {
struct sockaddr_un client_name; /* 工作套接字地址结构 */
socklen_t client_name_len; /* 套接字地址结构的大小 */
int client_socket_fd; /* 处理客户端连接的套接字文件描述符 */
// 接受连接
client_socket_fd = accept(socket_fd, (struct sockaddr*) &client_name, &client_name_len);
// 调用 server() 处理连接
client_sent_quit_message = server(client_socket_fd);
// 关闭服务器端连接到客户端的套接字
close(client_socket_fd);
} while(!client_sent_quit_message);
// 删除套接字文件
close(socket_fd);
unlink(socket_name);
return 0;
}
// socket-client-interactive.c
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
// 将 text 的内容通过 socket_fd 代表的套接字发送
void send_text(int socket_fd, char* text)
{
// 输出字符串的长度(包含结尾的NUL字符)
int length = strlen(text) + 1;
write(socket_fd, &length, sizeof(length));
// 输出字符串
write(socket_fd, text, length);
}
int main()
{
const char* socket_name = "/tmp/socket";
char* message;
int socket_fd;
struct sockaddr_un name;
// 创建套接字
socket_fd = socket(PF_LOCAL, SOCK_STREAM, 0);
// 将服务器地址写入套接字地址结构
name.sun_family = AF_LOCAL;
strcpy(name.sun_path, socket_name);
// 连接套接字
connect(socket_fd, (struct sockaddr*) &name, SUN_LEN(&name));
while(1) {
printf(">");
scanf("%s", message);
fflush(stdin);
if (message == NULL) {
continue;
}
// 调用 send_text() 将制定消息写入套接字
send_text(socket_fd, message);
}
// 关闭套接字
close(socket_fd);
return 0;
}
// 关闭服务器端连接到客户端的套接字
close(client_socket_fd);
//这个不需要的!链路已经半关闭了,TIME_WAIT