Redis源码-3 网络编程

Redis 网络编程 开发一个server和client, client向server发送消息, server输出client内容
源代码 源码
准备工作:从redis源码中拷贝代码

cp /home/vagrant/github/server_installer/servers/redis/redis-6.2/src/zmalloc.* . cp /home/vagrant/github/server_installer/servers/redis/redis-6.2/src/anet.* . cp /home/vagrant/github/server_installer/servers/redis/redis-6.2/src/atomicvar.h . cp /home/vagrant/github/server_installer/servers/redis/redis-6.2/src/fmacros.h .

新建server.c
#include "stdio.h" #include "anet.h" #include "zmalloc.h" #include #include #include "sys/socket.h" #define NET_IP_STR_LEN 46 /* INET6_ADDRSTRLEN is 46, but we need to be sure */int main() { // 错误信息 char *neterr = zmalloc(10); printf("staring...\n"); // 端口6380 int serverSocket = anetTcpServer(neterr, 6380,"*" , 2); if ( ! neterr ) { printf("start err %s \n", neterr); return 1; } printf("listening...%d \n",serverSocket ); while(1){ int cfd; // 错误信息 char* err = zmalloc(20); char cip[NET_IP_STR_LEN]; int cport; cfd = anetTcpAccept(err, serverSocket, cip, sizeof(cip), &cport); if ( cfd == ANET_ERR ) continue; printf("accept...%d\n",cfd); char buf[1024]; recv(cfd, buf, sizeof(buf), MSG_WAITALL); printf("recv from %s:%d%s\n",cip, cport, buf); close(cfd); } close(serverSocket); }

新建client.c
#include "stdio.h" #include "anet.h" #include "zmalloc.h" #include #include #include "sys/socket.h" #define NET_IP_STR_LEN 46 /* INET6_ADDRSTRLEN is 46, but we need to be sure */int main() { // 错误信息 char *neterr = zmalloc(10); printf("staring...\n"); int port; port = 6380; char* addr; addr = "127.0.0.1"; int fd = anetTcpNonBlockConnect(NULL,addr,port); char * hello = "hello"; printf("send %s\n", hello); send(fd, hello, sizeof(hello),MSG_DONTWAIT ); close(fd); }

新建Makefile文件
all: server client @echo "anet demo"server : anet.o zmalloc.o server.o $(CC)-o $@$^client : anet.o zmalloc.o client.o $(CC)-o $@$^%.o: %.c $(CC) -O0 -DREDIS_TEST=1 -MMD -o $@ -c $<.PHONY: clean clean: rm -rf *.o *.d server client

解释
anet把封装的了socket编程的接口, 原先需要socket, bind, listen, accept , connect等接口封装为很少的接口,屏蔽了一些复杂的参数,开发网络编程更加接近Go、Python等高级语言。
输出
执行make后会生成client和server, 先启动server,再执行client。
server端输出
staring... listening...3 accept...4 recv from 127.0.0.1:60322hello

【Redis源码-3 网络编程】client端输出
staring... send hello

使用到的api
  • int anetTcpServer(char err, int port, char bindaddr, int backlog); -- 创建tcp服务
  • int anetTcpAccept(char err, int serversock, char ip, size_t ip_len, int *port); --监听anetTcpServer的网络请求
  • int anetTcpNonBlockConnect(char err, const char addr, int port); -- 连接tcp服务
文章思路
  • 动手实践是最快的学习方式。用能理解的方式,轻松的学习Redis,借鉴Redis, 并应用。
  • 不过分关注细节,从Api入手
码字不易,感谢点赞

    推荐阅读