|
发表于 2004-3-12 10:44:41
|
显示全部楼层
有几个不一样的地方:
1.如程序AF_UNIX标志
2.会在当前目录下生成一个文件,名字就是你问的那个define
3.用完后要删除这个文件,否则下次启动会出错
我也写了一个(对不起,并不健壮):先运行服务器,再运行客户客户有参数为: 你的可执行名 要连接的服务器名 要发的信息 (其中,要连的服务器名在服务器端sockaddr_un.sun_path中指定,我用strcpy拷的那个,客户不是连到这个名字,就无法连上,就如IP地址不对一样)
服务器:
[code:1]
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdio.h>
int main(){
int serv_sock,cli_sock;
int server_len,client_len;
struct sockaddr_un server_address;
struct sockaddr_un client_address;
unlink("linuxfans");
serv_sock = socket(AF_UNIX,SOCK_STREAM,0);
server_address.sun_family = AF_UNIX;
strcpy(server_address.sun_path, "linuxfans");
server_len = sizeof(server_address);
bind(serv_sock,(struct sockaddr*)&server_address,server_len);
listen(serv_sock,5);
while(1){
char message_from_client[256];
int get_count;
printf("Server process is running\n Wait connecting from client process\n");
client_len = sizeof(client_address);
cli_sock = accept(serv_sock,(struct sockaddr*)&client_address,&client_len);
get_count=read(cli_sock,message_from_client,sizeof(message_from_client));
message_from_client[get_count]='\0';
printf("Get message from client:%s\n",message_from_client);
//you may do something with message from client
write(cli_sock,"hello wsm!",11);
close(cli_sock);
}
}
[/code:1]
客户端:
[code:1]
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc,char** argv){
int socket_client;
int len;
struct sockaddr_un serv_addr;
int result;
char message[256];
int get_count;
if(argc!=3){
fprintf(stderr,"usage:%s linuxfans message(you want it to be send to server)\n",argv[0]);
exit(1);
}
socket_client = socket(AF_UNIX,SOCK_STREAM,0);
serv_addr.sun_family = AF_UNIX;
strcpy(serv_addr.sun_path,argv[1]);
len = sizeof(serv_addr);
result = connect(socket_client,(struct sockaddr*)&serv_addr,len);
if (result == -1){
perror("connect failed!\n");
exit(1);
}
write(socket_client,argv[2],256);
get_count=read(socket_client,message,sizeof(message));
message[get_count]='\0';
printf("message from server: \n %s\n ",message);
close(socket_client);
exit(0);
}
[/code:1] |
|