您的位置:首页 > 数据库 > Redis

基于hiredis的聊天客户端

2016-05-04 10:44 519 查看

基于hiredis的聊天客户端实现

Redis里面提供了pub/sub功能,可以使用这个功能实现简单的聊天客户端。

关于pub/sub功能,可以查看我的另一篇文章http://blog.csdn.net/qq_34788352/article/details/51312481

1.首先连接服务器

redisContext *conn = redisConnect("127.0.0.1",6380); //ip和port可以根据具体情况调整


2.连接上服务器,需要知道能够接入那个频道,因此需要获取当前所有的频道

redisReply *reply = (redisReply*)redisCommand(conn,"pubsub channels");
int number = reply->elements; //获得频道数量
int i=0;
while(i<number)
{
redisReply r = reply->element[i][0];
printf("%s\n",r.str);
i++;
}
freeReplyObject(reply);


redisReply结构体中保存着redisCommand执行后返回的结果。

redisReply结构体的定义如下:

typedef struct redisReply
{
int type; //REDIS_REPLY_*
long long integer; //如果type==REDIS_REPLY_INTEGER,返回的数值保存在integer中
size_t len; //字符串的长度
char *str; //如果type==REDIS_REPLY_ERROR||type==REDIS_REPLY_STRING,返回的字符串保存在str中
size_t elements; //数组的大小
struct redisReply **element; //如果type==REDIS_REPLY_ARRAY,返回的数组保存在redisReply **element中
}redisReply;


3.选择频道,发送聊天内容

char * channel = malloc(sizeof(char)*256);
scanf("%s",channel);
char* words = (char*)malloc(sizeof(char)*(1024+256));
char* talk = (char*)malloc(sizeof(char)*1024);

scanf("%s",talk);

strcat(words,"publish ");
strcat(words,channel);
strcat(words," ");
strcat(words,talk);

reply = redisCommand(conn,words);
feeReplyObject(reply);


4.退出聊天室

if(!strcmp(talk,"/")) //如果用户按下"/",则退出客户端
{
char command[256] = "unsubscribe ";
strcat(command,channel);
reply = redisCommand(conn,command);
freeReplyObject(reply);
}


以上就是所有的核心代码。现在这个客户端功能还十分简单,以后有时间再进一步开发。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  redis hiredis