Redis 网络编程
开发一个server和client, client向server发送消息, server输出client内容
源代码
源码
准备工作:从redis源码中拷贝代码
1
2
3
4
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
#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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#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文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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端输出
1
2
3
4
|
staring...
listening...3
accept...4
recv from 127.0.0.1:60322 hello
|
client端输出
1
2
|
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服务
码字不易,感谢点赞