最近在学习Linux网络编程,参考《TCP/IP网络编程》写下这个socket编程示例——基于TCP的echo服务器/客户端。echo服务器,顾名思义就是将收到的客户端数据原封不动地传回客户端。
无论多么复杂的TCP服务器,其函数调用顺序几乎都是socket -> bind -> listen -> accept -> read/write -> close
,因此掌握这些基本函数的使用方法是很重要的。以下是基于TCP的echo服务器的完整代码(附带详细注释):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 1024
// to handle errors
void errorHandling(char* message) {
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
int main(int argc, char *argv[]) {
// sockets of the server and the client
int serv_sock, clnt_sock;
// buffer zone
char message[BUF_SIZE];
// the length of the message received
int str_len;
// the ip addresses of the server and the client
struct sockaddr_in serv_adr, clnt_adr;
// the size of the client address
socklen_t clnt_adr_sz;
// check if the number of arguments is correct
if (argc != 3) {
printf("Usage: %s <IP Address> <Port>\n", argv[0]);
exit(1);
}
// get a server socket
serv_sock = socket(PF_INET, SOCK_STREAM, 0); // domain, service types (should be SOCK_STREAM because of TCP), detailed protocol(usually 0)
// if failed
if (serv_sock == -1)