pid = fork();
if(pid < 0) {
perror("cannot create the child process");
close(listen_fd);
return 1;
}
//当有客户端连接的时候,在子进程中进行客户端与服务端的通信
else if(pid == 0) {
while((len = read(com_fd, recv_buffer, 1024)) > 0) {
printf("Message from client(%d): %s\n", len, recv_buffer);
if(recv_buffer[0] == '@') {
break;
}
for(i = 0; i < len; i++) {
recv_buffer[i] = toupper(recv_buffer[i]);
}
write(com_fd, recv_buffer,len);
memset(recv_buffer, 0, 1024);
}
close(com_fd);
return 0;
}
//父进程直接结束此次循环等待下一个客户端进行连接
else {
close(com_fd);
}
}
return 0;
}
------------------------------------------------
//此为服务端的程序
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int connect_fd;
int ret;
char snd_buffer[1024];
int i;
int port;
int len;
static struct sockaddr_in srv_addr;
if(argc != 3) {
printf("Usage: %s server_ip_address port\n", argv[1]);
return 1;
}
port = atoi(argv[2]);
if((connect_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
perror("cannot creat communication socket");
return 1;
}
memset(&srv_addr, 0, sizeof(srv_addr));
srv_addr.sin_family = AF_INET;
srv_addr.sin_addr.s_addr = inet_addr(argv[1]);
srv_addr.sin_port = htons(port);
if((ret = connect(connect_fd, (struct sockaddr*)&srv_addr, sizeof(srv_addr))) == -1) {
perror("cannot connect to the server");
close(connect_fd);
return 1;
}
//memset(snd_buffer, 0, 1024);
while(1) {
memset(snd_buffer, 0, 1024);
write(STDOUT_FILENO, "input message: ", 15);
len = read(STDIN_FILENO, snd_buffer, 1024);
if(len > 0)
write(connect_fd, snd_buffer, len);
len = read(connect_fd, snd_buffer, len);
if(len > 0)
printf("Message from serverL %s\n", snd_buffer);
if(snd_buffer[0] == '@')
break;
}
close(connect_fd);
return 0;
}
当然,这属于老版本的socket程序,最新的socket编程推荐使用getaddrinfo()函数,这个函数是通过一个hints参数来当做地址的返回标准的。具体的getaddrinfo()函数如下:
struct addrinfo {
int ai_flags; //input flags
int ai_family; //address family
int ai_socktype; //SOCK_STREAM, SOCK_DGRAM
int ai_protocol; //socket protocol
size_t ai_addrlen; //size of structure pointed to by ai_addr
char *ai_cannonname; //canonical name of host
struct sockaddr *ai_addr; //pointer to socket address structure
struct addrinfo *ai_next; //next structure in linked list
};
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>