[!Tip]
看了套接字编程,先自己实现,出错了或者哪一步没头绪了,再来看这个文档。不要一上来,就无脑抄。
本实例旨在实现简单的echo服务,客户端发送数据给服务端,在服务端打印出来并且回发给客户端,并在客户端显示。
1. TCP服务端
TCPserver.c
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BACKLOG 10
#define BUFFER_SIZE 1024
int main(int argc, char *argv[])
{
if(2 != argc)
{
printf("Usage:%s portnumber\n", argv[0]);
return - 1;
}
/***1.create a socket***/
int fd_server = socket(AF_INET, SOCK_STREAM, 0); //TCP
if( - 1 == fd_server)
{
printf("%s\n", strerror(errno));
return - 1;
}
/***2.bind the socket***/
int listen_port = atoi(argv[1]);
struct sockaddr_in addr_server;
//memset(&addr_server, 0, sizeof(addr_server));
addr_server.sin_family = AF_INET;
addr_server.sin_port = htons(listen_port);
addr_server.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(fd_server, (struct sockaddr*) &addr_server, sizeof(addr_server)) == - 1)
{
printf("%s\n", strerror(errno));
return - 1;
}
/***3.listen the socket***/
if(listen(fd_server, BACKLOG) == - 1)
{
printf("%s\n", strerror(errno));
return - 1;
}
/***4.accept the requirement of some client***/
struct sockaddr_in addr_client;
int len_addr_client = sizeof(addr_client);
int fd_client = accept(fd_server, (struct sockaddr*) &addr_client, &len_addr_client);
if( - 1 == fd_client)
{
printf("%s\n", strerror(errno));
return - 1;
}
/****5.serve the client******/
char buf[BUFFER_SIZE];
int size;
while(1)
{
/***read from client***/
size = recv(fd_client, buf, sizeof(buf), 0);
buf[size] = '\0';
printf("%s\n", buf);
/***write to client***/
size = send(fd_client, buf, strlen(buf), 0);
}
/****6.close the socket******/
close(fd_server);
close(fd_client);
}
2. TCP客户端
TCPclient.c
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[])
{
if(3 != argc)
{
printf("Usage:%s hostname portnumber\n", argv[0]);
return - 1;
}
/***1.create a socket***/
int fd_client = socket(AF_INET, SOCK_STREAM, 0); //TCP
if( - 1 == fd_client)
{
printf("%s\n", strerror(errno));
return - 1;
}
/***2.connect to the server***/
int portnumber = atoi(argv[2]);
struct sockaddr_in addr_server;
addr_server.sin_family = AF_INET;
addr_server.sin_port = htons(portnumber);
if(0 == inet_pton(AF_INET, argv[1], (void*) &addr_server.sin_addr.s_addr))
{
printf("Invalid address.\n");
return - 1;
}
if(connect(fd_client, (struct sockaddr*) &addr_server, sizeof(addr_server)) == - 1)
{
printf("%s\n", strerror(errno));
return - 1;
}
/****3.get the server******/
char buf[BUFFER_SIZE];
int size;
while(1)
{
/***write to server***/
scanf("%s", buf);
size = send(fd_client, buf, strlen(buf), 0);
/***read from server***/
size = recv(fd_client, buf, BUFFER_SIZE, 0);
buf[size] = '\0';
printf("%s\n", buf);
}
/****4.close the socket******/
close(fd_client);
}
2.3 测试结果
运行服务端程序./TCPserver 2000
:
运行客户端程序./TCPclient 127.0.0.1 2000
: