/*使用套接字实现进程间通信
*进程之间不共享数据
* */
# include <iostream>
# include <unistd.h>
# include <sys/un.h>
# include <sys/types.h>
# include <stdio.h>
# include <stdlib.h>
# include <sys/socket.h>
# include <string.h>
# define SOCKET_FILE "./mysocket"
using namespace std;
//小写转大写
void work(char *buf1) {
char *p = buf1;
while (*p) {
if (*p >= 'a' && *p <= 'z') {
*p += 'A' - 'a';
}
p++;
}
}
//创建客户端
void Client (int& fd)
{
int ret;
//客户端地址
struct sockaddr_un addr_server;
//1. 创建套接字
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
perror("套接字创建失败.");
exit(1);
}
//2. 设置服务器地址
addr_server.sun_family = AF_UNIX;
strcpy(addr_server.sun_path, SOCKET_FILE);
//3. 向服务器发起连接
ret = connect(fd, (struct sockaddr*)&addr_server, sizeof(addr_server));
if (ret < 0) {
perror("连接失败.");
exit(1);
}
printf("已经连接到服务器.\n");
}
void ClientWork(int fd)
{
int ret;
char buf1[256] = {'0',} ;
while(1){
printf("请输入:");
fgets(buf1, sizeof(buf1), stdin); //从键盘获取数据存在buf
if (strcmp (buf1,"exit\n") == 0){
printf("用户要求退出.\n");
exit(0);
}
//向服务器发送数据
ret = write(fd, buf1, strlen(buf1)+1);
memset(buf1,'\0',256);
if (ret < 0) {
perror("写失败.\n");
exit(1);
} else if (ret == 0) {
printf("没有输入数据.\n");
}
ret = read(fd,buf1,sizeof(buf1));
printf("收到服务器返回信息: \033[32m%s\033[0m \n", buf1);
memset(buf1,'\0',256);
}
}
void Server(int& server_fd, int& client_fd)
{
int ret;
//服务器地址
struct sockaddr_un addr_server;
struct sockaddr_un addr_client;
socklen_t addr_len = sizeof(addr_client);
//1. 删除该服务器套接字准备使用的文件(如果有)
unlink(SOCKET_FILE);
//2. 创建一个文件系统套接字
server_fd = socket(AF_UNIX,SOCK_STREAM,0);
if (server_fd < 0) {
perror("创建套接字失败.");
exit(1);
}
//3. 设置服务器地址
addr_server.sun_family = AF_UNIX;
strcpy(addr_server.sun_path, SOCKET_FILE);
//4. 绑定套接字
ret = bind(server_fd, (struct sockaddr*)&addr_server,sizeof(addr_server));
if (ret < 0) {
perror("绑定失败.");
exit(1);
}
//5. 创建套接字队列
listen(server_fd, 3);
//6. 循环处理客户端的请求
printf("正在等待客户端接入...\n");
client_fd = accept(server_fd, (struct sockaddr*)&addr_client, &addr_len);
printf("客户端已经接入.\n");
}
void ServerWork(int server_fd, int client_fd){
int ret;
char buf2[512];
//读取客户端信息
while (1) {
ret = read(client_fd, buf2, sizeof(buf2));
if (ret < 0) {
perror("读失败.");
exit(1);
} else if (ret == 0) {
//该客户端关闭后,返回0
printf("对端关闭.\n");
exit(1);
} else {
printf("服务器收到 : \033[31m%s\033[0m\n", buf2);
}
//处理收到的数据并把处理结果发送给客户端
work(buf2);
ret = write(client_fd, buf2, strlen(buf2)+1);
memset(buf2,'\0',256);
if (ret < 0) {
perror("写失败.");
exit(1);
} else if (ret == 0) {
printf("对端关闭.\n");
exit(1);
}
}
}
int main(){
int fp = fork ();
if (0 == fp){ //---------------------子进程
int fd;
sleep(3);//休眠3s保证服务器先启动
Client(fd);
sleep(1);
ClientWork(fd);
} else { //-----------------父进程
int server_fd;
int client_fd;
Server(server_fd,client_fd);
ServerWork(server_fd,client_fd);
}
}