class="markdown_views prism-kimbie-light">
Linux 嵌入式 C 实现简单的网络聊天室
版权声明:
https://blog.csdn.net/qq_39603089/article/details/85080802
使用C/S 模式,参考下图:
原代码可从直接下载,与所示代码稍有不同,有所改进与完善。
https://blog.csdn.net/qq_39603089/article/details/85327599
服务端无用户界面;
客户端情看:
https://blog.csdn.net/qq_39603089/article/details/85080521
服务端代码:
/*-------------------------服务器端chat_server.c-------------------------------
time:2018/12/18
author:zyb-dy
*/
#include
#include
#include
#include
#include //数据类型定义
#include //文件属性
#include //定义数据结构sockaddr_in
#include //提供socket函数和数据结构
#include
#include
#include
#include
#include
#include
#include
#include
#include //线程
#define THREAD_NUMBER 30 //最大链接数
#define MYPORT 8787
#define BUFFER_SIZE 1024
#define WELCOME "Welcome"
struct Users{ //表示用户与线程之间的关联
char name[50];
pthread_t thread;
char buf[BUFFER_SIZE];
int client_fd;
char address[20];
int login; //是否在线
}users[THREAD_NUMBER];
int sem_id;
//返回系统时间
void get_now_time(char *nt){
time_t tmpcal_ptr;
struct tm *tmp_ptr = NULL;
time(&tmpcal_ptr);
tmp_ptr = localtime(&tmpcal_ptr);
sprintf(nt,"%d:%d:%d", tmp_ptr->tm_hour, tmp_ptr->tm_min, tmp_ptr->tm_sec);
}
int init_sem(int sem_id, int init_value){
union semun{
int val;
struct semid_ds *buf;
unsigned short *array;
};
union semun sem_union;
sem_union.val = init_value;
if(semctl(sem_id, 0, SETVAL, sem_union) == -1){
syslog(LOG_ERR, "Initialize semaphore");
perror("Initialize semaphore");
return -1;
}
return 0;
}
int del_sem(int sem_id){
union semun{
int val;
struct semid_ds *buf;
unsigned short *array;
};
union semun sem_union;
if(semctl(sem_id, 1, IPC_RMID, sem_union)==-1){
syslog(LOG_ERR, "Delete semaphore");
perror("Delete semaphore");
return -1;
}
}
//P 操作函数
int sem_p(int sem_id){
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = -1;
sem_b.sem_flg = SEM_UNDO;
if(semop(sem_id, &sem_b, 1)==-1){
syslog(LOG_ERR, "P operation");
perror("P operation");
return -1;
}
return 0;
}
//V 操作函数
int sem_v(int sem_id){
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = 1;
sem_b.sem_flg = SEM_UNDO;
if(semop(sem_id, &sem_b, 1) == -1){
syslog(LOG_ERR, "V operation");
perror("V operation");
return -1;
}
return 0;
}
//发送给个人
void send_all(char loadsend[BUFFER_SIZE]){
int j;
for(j=0;j1){
buf[j]=s[i];
j++;
}else if(n==1){
if(s[i]==':'){
n++;
name[j]='