2010年(7)
分类: LINUX
2010-05-01 15:27:32
#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';
我们在这里创建一个socket
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
为socket赋名称,要与server端的名称相同
address.sun_family = AF_UNIX;
strcpy(address.sun_path, "server_socket");
len = sizeof(address);
现在连接服务器端的也就是server那面的socket
result = connect(sockfd, (struct sockaddr *)&address, len);
if(result == -1) {
perror("oops: client1");
exit(1);
}
现在我们可以在客户端读写socket了
write(sockfd, &ch, 1);
read(sockfd, &ch, 1);
printf("char from server = %c\n", ch);
close(sockfd);
exit(0);
}
#include <sys/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;
移除旧的socket,防止冲突,然后创建一个未命名的socket
unlink("server_socket");
server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
为创建的这个socket赋名称,与客户端的保持一致的名称
server_address.sun_family = AF_UNIX;
strcpy(server_address.sun_path, "server_socket");
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
创建一个连接队列等待客户端来链接
listen(server_sockfd, 5);
while(1) {
char ch;
printf("server waiting\n");
接受连接
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,
(struct sockaddr *)&client_address, &client_len);
开始与客户端读写的操作
read(client_sockfd, &ch, 1);
ch++;
write(client_sockfd, &ch, 1);
close(client_sockfd);
}
}
[root@localhost qinj]# ./server1 &
[root@localhost qinj]# ./client1
char from server = B