[1] 服务器模型
1. 轮询(循环)
用一个任务(一个进程或线程为多个客户端轮流服务)
2. 并发(同时处理)
给每个客户端开启一个任务,专门为它服务
[2] 文件服务器(并发)
1. 轮询(循环)
用一个任务(一个进程或线程为多个客户端轮流服务)
2. 并发(同时处理)
给每个客户端开启一个任务,专门为它服务
[2] 文件服务器(并发)
[函数说明]
int sprintf(char *str, const char *format, ...); //"const char *format, ..." -->字符串-->str
//"%%0%dd" --> "%010d"
void *memcpy(void *dest, const void *src, size_t n);
void bzero(void *s, size_t n);
#ifndef __PROTOCOL_H__
#define __PROTOCOL_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define FUNC_LEN 1
enum {
FUNC_LOGIN = 1,
FUNC_CHAT,
FUNC_QUIT,
FUNC_END
};
int prot_pack_login(char *packet, const char *name);
int prot_pack_chat(char *packet, const char *content);
int prot_pack_quit(char *packet);
int prot_get_func(const char *packet);
const char *prot_get_content(const char *packet);
#endif // __PROTOCOL_H__
/*
* +-------------+--------------------+--------+
* | 功能号(1B) | 包体 | 功能 |
* +-------------+--------------------+--------+
* | '1' | 用户名(20B) | 登录 |
* +-------------+--------------------+--------+
* | '2' | 内容(1024B) | 聊天 |
* +-------------+--------------------+--------+
* | '3' | "" | 退出 |
* +-------------+--------------------+--------+
*
*/
#include "protocol.h"
// 登录
// len = prot_pack_login(buf, "wangjie");
int prot_pack_login(char *packet, const char *name)
{
int len = 0;
// 功能号
sprintf(packet + len, "%d", FUNC_LOGIN);
len += FUNC_LEN;
// 用户名
strcpy(packet + len, name);
len += strlen(name);
return len;
}
// 聊天
// len = prot_pack_chat(buf, "hello");
int prot_pack_chat(char *packet, const char *content)
{
int len = 0;
// 功能号
sprintf(packet + len, "%d", FUNC_CHAT);
len += FUNC_LEN;
// 内容
strcpy(packet + len, content);
len += strlen(content);
return len;
}
// 退出
// len = prot_pack_quit(buf);
int prot_pack_quit(char *packet)
{
int len = 0;
// 功能号
sprintf(packet + len, "%d", FUNC_QUIT);
len += FUNC_LEN;
return len;
}
// 获得功能号
// func = prot_get_func(packet);
int prot_get_func(const char *packet)
{
char buf[FUNC_LEN + 1];
memcpy(buf, packet, FUNC_LEN);
buf[FUNC_LEN] = '\0';
return atoi(buf);
}
// 获取包体内容
// p = prot_get_content(buf);
const char *prot_get_content(const char *packet)
{
return packet + FUNC_LEN;
}