日期:2014-05-16 浏览次数:20701 次
include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<sys/un.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int sockfd;
int len;
struct sockaddr_un address;
int result;
char ch='A';
sockfd=socket(AF_UNIX,SOCK_STREAM,0);
//给套接字命名
address.sun_family=AF_UNIX;
strcpy(address.sun_path,"server_socket");
len=sizeof(address);
//将套接字连接到服务器
result=connect(sockfd,(struct sockaddr*)&address,len);
if(result==-1)
{
perror("oops:client1");
exit(EXIT_FAILURE);
}
//通过套接字进行读写
write(sockfd,&ch,1);
read(sockfd,&ch,1);
printf("char form server =%c\n",ch);
close(sockfd);
exit(EXIT_SUCCESS);
}
服务器程序代码:
#includeisys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<sys/un.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int server_sockfd, client_sockfd;
int server_len,client_len;
struct sockaddr_un server_address;
struct sockaddr_un client_address;
//删除以前的套接字,为服务器创建一个未命名的套接字
unlink("server_socket");
server_sockfd=socket(AF_UNIX,SOCK_STREAM,0);
//命名套接字
server_address.sun_family=AF_UNIX;
strcpy(server_address.sun_path,"server_socket");
server_len=sizeof(server_address);
bind(server_sockfd,(struct address*)&server_address,server_len);
listen(server_sockfd,5);
while(1)
{
char ch;
printf("server waiting\n");
//接受一个请求
client_len=sizeof(client_address);
&nb