//socket本地编程,服务器端
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include <sys/un.h>
#include<string.h>
#include<arpa/inet.h>
#include<unistd.h>
#include <iostream>
#include<stdio.h>
#include <errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<utility>
#include<string>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/time.h>
using namespace std;
#define BUFF_LEN 1024
int main(){
unlink("sock_test");//删除文件
struct sockaddr_un server_addr;
struct sockaddr_un client_addr;
//int client_addr_size = sizeof(struct client_addr);
int server_sock,client_sock;
server_sock = socket(PF_UNIX,SOCK_STREAM,0);//创建服务器套接字
if(-1==server_sock){
perror("server_sock created failed");
return -1;
}
cout<<"sercer_sock created"<<endl;
memset(&server_addr,0,sizeof(server_addr));
server_addr.sun_family = PF_UNIX;
strcpy(server_addr.sun_path,"sock_test");
if(-1==bind(server_sock,(struct sockaddr*)&server_addr,sizeof(server_addr))){
perror("bind failed");
return -1;
}
cout<<"bind success"<<endl;
if(-1==listen(server_sock,3)){
perror("listen failed");
return -1;
}
cout<<"linstening"<<endl;
socklen_t client_addr_len = sizeof(client_addr);
char *recv_buffer = new char[BUFF_LEN];
const char *signal = "recv finished";
int send_len;
int recv_len;
while(1){
cout<<"waiting for accept"<<endl;
client_sock = accept(server_sock,(struct sockaddr * )&client_addr,&client_addr_len);
if(-1==client_sock){
perror("accept failed");
return -1;
}
cout<<"accept success"<<endl;
recv_len = recv(client_sock,recv_buffer,BUFF_LEN,0);
cout<<"rec_len="<<recv_len<<endl;
strcpy(recv_buffer+recv_len,signal);
send_len = send(client_sock,recv_buffer,BUFF_LEN,0);
cout<<"send finished"<<endl;
close(client_sock);
}
delete [] recv_buffer;
}
//客户端
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include <sys/un.h>
#include<string.h>
#
socket本地通信
最新推荐文章于 2024-07-10 11:16:10 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)