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 <sys/socket.h>
#include <unistd.h>
#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 <sys/socket.h>
#include <unistd.h>
#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:60322 hello
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 服务