linux下的chat程序设计

2019-07-13 03:37发布

linux下通过socket实现聊天功能,代码如下: 头文件:Unp1.h #include /* basic system data types */ #include /* basic socket definitions */ #include /* timeval{} for select() */ #include /* timespec{} for pselect() */ #include /* sockaddr_in{} and other Internet defns */ #include /* inet(3) functions */ #include #include /* for nonblocking */ #include #include #include #include #include #include /* for S_xxx file mode constants */ #include /* for iovec{} and readv/writev */ #include #include #include #define MAXLINE 4096 #define LISTENQ 1024
chat.h代码如下: /*chat.h*/ #ifndef __CHAT_H #define __CHAT_H #include "unp1.h" #define MAXUSERS 3 /* used to write number of n bytes to socket buffer*/ ssize_t writen(int fd,const void * vptr,size_t n); /*used to read number of n bytes from the socket buffer*/ ssize_t readn(int fd,void *vptr,size_t n); struct chat_struct{ int sock_fd; char user_id[20]; struct in_addr user_ipaddr; int next_char; int data_pos; struct client_cmd{ int cmd_type; char user_id[20]; }cmd; char buffer[MAXLINE]; int slot_status; }chater[MAXUSERS]; #define SLOT_FREED 0 #define SLOT_OCCUPIED 1 #define TELL_SOMEONE 1 #define CHAT_ALL 2 /*the two types of the user inputed*/ #define CHATER_LOGOUT 1 #define CHATER_ENTER_A_CMD 2 /*define the message notice to the users*/ char message[4][50]={"to many users in the system. ", "can not find that user. '", "input your user_id: ", "error command "}; /*it is used to select a free slot to the user,if there is not ,it will create one */ void get_free_slot(int sock_fd,char *user_name) { int j,flags; printf("enter get_free_slot. "); for(j=0;j