一、服务端 这是一个字节流类型的本地套接字服务器端例子。在这个例子中,服务器程序打开本地套接字后,接收客户端发送来的字节流,并往客户端回送了新的字节流。
int main(int argc, char **argv) { if (argc != 2) { error(1, 0, “usage: unixstreamserver <local_path>”); } int listenfd, connfd; socklen_t clilen; struct sockaddr_un cliaddr, servaddr; listenfd = socket(AF_LOCAL, SOCK_STREAM, 0); if (listenfd < 0) { error(1, errno, “socket create failed”); } char *local_path = argv[1]; unlink(local_path); bzero(&servaddr, sizeof(servaddr)); servaddr.sun_family = AF_LOCAL; strcpy(servaddr.sun_path, local_path); if (bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {\ error(1, errno, “bind failed”); } if (listen(listenfd, LISTENQ) < 0) { error(1, errno, “listen failed”); } clilen = sizeof(cliaddr); if ((connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen)) < 0) { if (errno == EINTR) error(1, errno, “accept failed”); /* back to for() */ else error(1, errno, “accept failed”); } char buf[BUFFER_SIZE]; while (1) { bzero(buf, sizeof(buf)); if (read(connfd, buf, BUFFER_SIZE) == 0) { printf(“client quit”); break; } printf(“Receive: %s”, buf); char send_line[MAXLINE]; sprintf(send_line, “Hi, %s”, buf); int nbytes = sizeof(send_line); if (write(connfd, send_line, nbytes) != nbytes) error(1, errno, “write error”); } close(listenfd); close(connfd); exit(0); }<
二、客户端
int main(int argc, char **argv) { if (argc != 2) { error(1, 0, “usage: unixstreamclient <local_path>”); } int sockfd; struct sockaddr_un servaddr; sockfd = socket(AF_LOCAL, SOCK_STREAM, 0); if (sockfd < 0) { error(1, errno, “create socket failed”); } bzero(&servaddr, sizeof(servaddr)); servaddr.sun_family = AF_LOCAL; strcpy(servaddr.sun_path, argv[1]); if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { error(1, errno, “connect failed”); } char send_line[MAXLINE]; bzero(send_line, MAXLINE); char recv_line[MAXLINE]; while (fgets(send_line, MAXLINE, stdin) != NULL) { int nbytes = sizeof(send_line); if (write(sockfd, send_line, nbytes) != nbytes) error(1, errno, “write error”); if (read(sockfd, recv_line, MAXLINE) == 0) error(1, errno, “server terminated prematurely”); fputs(recv_line, stdout); } exit(0); }<
免责声明:文章内容来自互联网,本站不对其真实性负责,也不承担任何法律责任,如有侵权等情况,请与本站联系删除。
转载请注明出处:本地套接字的使用 https://www.yhzz.com.cn/a/14749.html