博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[linux] unix domain socket 例子
阅读量:4250 次
发布时间:2019-05-26

本文共 2536 字,大约阅读时间需要 8 分钟。

服务器:

#include 
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 80char *socket_path = "server.socket";int main(void){ struct sockaddr_un serun, cliun; socklen_t cliun_len; int listenfd, connfd, size; char buf[MAXLINE]; int i, n; if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { perror("socket error"); exit(1); } memset(&serun, 0, sizeof(serun)); serun.sun_family = AF_UNIX; strcpy(serun.sun_path, socket_path); size = offsetof(struct sockaddr_un, sun_path) + strlen(serun.sun_path); unlink(socket_path); if (bind(listenfd, (struct sockaddr *)&serun, size) < 0) { perror("bind error"); exit(1); } printf("UNIX domain socket bound\n"); if (listen(listenfd, 20) < 0) { perror("listen error"); exit(1); } printf("Accepting connections ...\n"); while(1) { cliun_len = sizeof(cliun); if ((connfd = accept(listenfd, (struct sockaddr *)&cliun, &cliun_len)) < 0){ perror("accept error"); continue; } while(1) { n = read(connfd, buf, sizeof(buf)); if (n < 0) { perror("read error"); break; } else if(n == 0) { printf("EOF\n"); break; } printf("received: %s\n", buf); for(i = 0; i < n; i++) { buf[i] = toupper(buf[i]); } write(connfd, buf, n); } close(connfd); } close(listenfd); return 0;}

客户端:

#include 
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 80char *client_path = "client.socket";char *server_path = "server.socket";int main() { struct sockaddr_un cliun, serun; int len; char buf[100]; int sockfd, n; if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0){ perror("client socket error"); exit(1); } // 一般显式调用bind函数,以便服务器区分不同客户端 memset(&cliun, 0, sizeof(cliun)); cliun.sun_family = AF_UNIX; strcpy(cliun.sun_path, client_path); len = offsetof(struct sockaddr_un, sun_path) + strlen(cliun.sun_path); unlink(cliun.sun_path); if (bind(sockfd, (struct sockaddr *)&cliun, len) < 0) { perror("bind error"); exit(1); } memset(&serun, 0, sizeof(serun)); serun.sun_family = AF_UNIX; strcpy(serun.sun_path, server_path); len = offsetof(struct sockaddr_un, sun_path) + strlen(serun.sun_path); if (connect(sockfd, (struct sockaddr *)&serun, len) < 0){ perror("connect error"); exit(1); } while(fgets(buf, MAXLINE, stdin) != NULL) { write(sockfd, buf, strlen(buf)); n = read(sockfd, buf, MAXLINE); if ( n < 0 ) { printf("the other side has been closed.\n"); }else { write(STDOUT_FILENO, buf, n); } } close(sockfd); return 0;}

转载地址:http://gtkei.baihongyu.com/

你可能感兴趣的文章
Fiddler屏蔽某些url的抓取方法
查看>>
浅析CSS中的overflow属性
查看>>
浅析HTML <label> 标签的 for 属性
查看>>
H5使用Selectors API简化选取操作
查看>>
记录我人生新的开始
查看>>
关于System.arraycopy方法的使用
查看>>
java基本概念(一)
查看>>
java基本概念(二)
查看>>
简易的ATM机
查看>>
旧版本的ATM
查看>>
关于super()
查看>>
关于JAVA中GUI的使用
查看>>
接口的简单使用
查看>>
关于接口的几点
查看>>
自己封装的一个简单组件:文字标签 文本框
查看>>
集合的一些概念总结
查看>>
几个常见的关于日期的SQL
查看>>
常见约束、事务及其他查询语句
查看>>
关于jdbc
查看>>
利用jdbc做的一个简单系统(接上一篇)
查看>>