logo头像

创作生活,分享学习

一步步写c++ server程序(1)---TCP服务端

前言

整个系列的文章目的是写一个MessageServer,用于进程间通信的。并制定一个网络协议可以不同设备之间不同进程之间通信。协议暂时命名为N19协议。

一个简单的TCPServer

先写一个简单的TCP server,用Telnet作为客户端测试
TCPServer.cpp:

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include <arpa/inet.h>
#include<unistd.h>


#define MAXLINE 1024
#define SERVER_PORT 8888

int main(int argc, char *argv[])
{
int ret = -1;
int port = SERVER_PORT; //默认端口

if( argc == 2)
{
port = atoi(argv[1]);//可以配置第一个参数为端口
}
printf("Server port [%d]\n", port);

int listen_fd = 0;
listen_fd = socket(AF_INET, SOCK_STREAM, 0); //TCP
if(listen_fd < 0)
{
printf("listen_fd = %d error:[%s]\n", listen_fd, strerror(errno));
return 0;
}

struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
ret = bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in));
if(ret < 0)
{
printf("ret = %d error:[%s]\n", ret, strerror(errno));
return 0;
}
ret = listen(listen_fd, SOMAXCONN);
if(ret < 0)
{
printf("ret = %d error:[%s]\n", ret, strerror(errno));
return 0;
}
while(1)
{
int connect_fd = 0;
socklen_t addrlen = 0;
struct sockaddr_in accept_addr;
connect_fd = accept(listen_fd, (struct sockaddr *) &accept_addr, &addrlen);
if( connect_fd < 0)
{
printf("accept error:[%s]\n", strerror(errno));
continue;
}
char send_buff[MAXLINE] = {0};
snprintf(send_buff, MAXLINE, "welcome,your address is [%s:%d]\n", inet_ntoa(accept_addr.sin_addr), accept_addr.sin_port);
ret = write(connect_fd, send_buff, strlen(send_buff));
if( ret < 0)
{
printf("send error: %s\n", strerror(errno));
return 0;
}
for(;;)
{
char recv_buff[MAXLINE] = {0};
int buff_len = 0;
buff_len = read(connect_fd, recv_buff, MAXLINE);
recv_buff[buff_len] = '\0';
if(strstr(recv_buff, "bye"))
{
break;
}
snprintf(send_buff, MAXLINE, "you said:%s", recv_buff);
ret = write(connect_fd, send_buff, strlen(send_buff));
if( ret < 0)
{
printf("send error: %s\n", strerror(errno));
break;
}
}

close(connect_fd);
}
close(listen_fd);
return 0;
}

编译运行:

1
2
gcc -o TCPServer TCPServer.cpp
./TCPServer
1
2
3
4
5
6
7
8
9
10
11
lorne@DESKTOP-06O9LMV:/mnt/c/Users/Lorne$ telnet 127.0.0.1 8888
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
welcome,your address is [153.127.0.0:6210]
asda
you said:asda
asd
you said:asd
bye bye
Connection closed by foreign host.
支付宝打赏 微信打赏

臭不要脸地放出了打赏码