📄 network.c
字号:
#include "global.h"
/*receive messages*/
void receive_mes(int connfd)
{
int i = 0;
int j = 0;
int n = 0;
int nn = 0;
int res;
int len;
char c;
char buff[MAX_MES];
char temp[MAX_MES];
char num[MAX_NUM];
char * mes;
pthread_t tid;
pthread_attr_t thread_attr;
if((res=pthread_attr_init(&thread_attr)) != 0) {
log_err("Attribute creation fails!\n");
}
if((res=pthread_attr_setdetachstate(&thread_attr,
PTHREAD_CREATE_DETACHED)) != 0) {
log_err("Seting detach attribute fails!\n");
}
buff[0] = '\0';
// while((n=read(connfd,&c,1))>0) {
// buff[count] = c;
// count += n;
// if(count > MAX_MES)
// return;
// buff[count] = '\0';
// /*a message has been red*/
// if(c == '\0') {
//#ifdef Debug
// printf("%s\n",buff);
//#endif
// mes = (char *)malloc(sizeof(char)*(count+20));
// if(!mes) {
// log_err("malloc fail!\n");
// }
// sprintf(mes,"%d,%s",connfd,buff);
// if((res=pthread_create(&tid,&thread_attr,(void * (*)(void *))handle_mes, (void *)mes)) != 0) {
// log_err("Creating thread fail!\n");
// }
// buff[0] = '\0';
// n = 0;
// count = 0;
// }
// }
while((n=read(connfd,&c,1))>0) {
num[i] = c;
if(c == '\n') {
num[i] = '\0';
len = atoi(num)+1;
buff[0] = '\0';
j = 0;
while((nn=read(connfd,temp,len))>0) {
strncat(buff,temp,nn);
j += nn;
buff[j] = '\0';
len -= nn;
if(len == 0)
break;
}
j--;
buff[j] = '\0';
#ifdef Debug
printf("%s\n",buff);
#endif
mes = (char *)malloc(sizeof(char)*(j+20));
if(!mes) {
log_err("malloc fail!\n");
}
sprintf(mes,"%d,%s",connfd,buff);
if((res=pthread_create(&tid,&thread_attr,(void * (*)(void *))handle_mes, (void *)mes)) != 0) {
log_err("Creating thread fail!\n");
}
i = 0;
} else
i++;
}
if(n < 0) {
fprintf(stderr,"read error\n");
do_quit(connfd);
return;
}
do_quit(connfd);
}
/*send message*/
void send_mes(char * buff,int connfd)
{
int n;
int i;
char temp[MAX_MES+10];
n = strlen(buff);
sprintf(temp,"%d\n%s\n",n,buff);
n = strlen(temp);
i = write(connfd,temp,n);
if(i < n) {
log_err("write error!\n");
}
}
/*send message with a user name at the top of
* the it*/
void send_name_mes(char * buff,char * name,int connfd)
{
int n;
int i;
char temp[MAX_MES+10];
bucket_list l;
n = strlen(buff);
sprintf(temp,"<%s> %d\n%s\n",name,n,buff);
n = strlen(temp);
i = write(connfd,temp,n);
if(i < n) {
log_err("write error!\n");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -