- 论坛徽章:
- 0
|
//chat_serv.c
#include<stdlib.h>
#include<stdio.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#include<unistd.h>
#include<fcntl.h>
#define MAXDATASIZE 256
#define SERVPORT 5555
#define BACKLOG 1 //最大同时连接请求
#define STDIN 0
int main(void)
{
FILE *fp;
int sockfd, client_fd; //监听socket.sock_fd, 数据传输socket.new_fd
int sin_size;
struct sockaddr_in my_addr, remote_addr; //本机地址信息, 客户端地址信息
char buf[256]; //用于聊天的缓冲区
char buf_name[256];
char send_str[256];
int recvbytes;
fd_set rfd_set, wfd_set, efd_set; // 被select监听的读写异常处理的文件描述符集合
struct timeval timeout;
int ret;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) ==-1)
{
herror("socket\n");
exit(1);
}
bzero(&my_addr,sizeof(struct sockaddr_in)); //端填充sockaddr结构
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(SERVPORT);
inet_aton("127.0.0.1", &my_addr.sin_addr);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
{
herror("bind");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1)
{
herror("listen");
exit(1);
}
sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size)) ==-1)
{
herror("accept");
exit(1);
}
fcntl(client_fd, F_SETFD, O_NONBLOCK);//将服务器设置非阻塞
recvbytes = recv(client_fd, buf_name, MAXDATASIZE, 0);//接收从客户端传来的用户名
buf_name[recvbytes] = '\0';
printf("recv one account : %s\n", buf_name);
printf("server : ");
fflush(stdout);
if ((fp = fopen("name.txt", "a+")) ==NULL)
{
printf("can not open file, exit ... \n");
exit(1);
}
fprintf(fp, "%s\n", buf_name); //将用户名写入name.txt
fclose(fp);
while(1)
{
FD_ZERO(&rfd_set);
FD_ZERO(&wfd_set);
FD_ZERO(&efd_set);
FD_SET(STDIN, &rfd_set);
FD_SET(client_fd, &rfd_set);
FD_SET(client_fd, &efd_set);
timeout.tv_sec = 10; //超时设置
timeout.tv_usec = 0;
ret = select(client_fd+1, &rfd_set, &wfd_set, &efd_set, &timeout);
if (ret == 0)
{
continue;
}
if (ret < 0)
{
herror("select error : ");
exit(-1);
}
if (FD_ISSET(STDIN, &rfd_set))
{
fgets(send_str, 255, stdin); //获取从标准输入输入的内容
send_str[strlen(send_str)-1] = '\0';
if (strncmp("exit", send_str, 4) == 0)
{
close(client_fd);
close(sockfd);
exit(0);
}
send(client_fd, send_str, strlen(send_str), 0);
fprintf(stderr, "server :");
}
if (FD_ISSET(client_fd, &rfd_set))
{
recvbytes = recv(client_fd, buf, MAXDATASIZE, 0);//接收从客户端传来的聊天程序
if (recvbytes == 0)
{
puts("\n");
close(client_fd);
close(sockfd);
exit(0);
}
buf[recvbytes] = '\0';
fprintf(stderr,"\n %s : %s\n", buf_name, buf);
printf("server : ");
fflush(stdout);
}
if (FD_ISSET(client_fd, &efd_set))
{
close(client_fd);
close(sockfd);
exit(0);
}
} //end while
}//end main
[ 本帖最后由 cnlag01 于 2009-9-13 21:56 编辑 ] |
|