搭建TCP服务器和客户端

服务器端流程

1创建并打开套接字socket

2.绑定IP地址和端口号bind

3.创建监听队列listen

4.等待并建立连接accept

5接收数据recv

6.关闭套接字close

用父子进程实现客户端与服务器端的互相发送和接收消息

#include 
#include 
#include 
#include 
#include 
#include 


int main()
{
	//创建并打开套接字
	int sockFd = socket(PF_INET, SOCK_STREAM, 0);
	if(sockFd < 0)
	{
		perror("socket error!");
		return -1;
	}
	printf("socket ok!\n");


	//绑定IP地址和端口号
	struct sockaddr_in servAddr = {0};    //服务器的地址信息
	servAddr.sin_family = PF_INET;
	servAddr.sin_port = htons(10000);     //端口号
	//"0.0.0.0"当前主机IP是多少就绑定多少
	servAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
	int ret = bind(sockFd, (struct sockaddr *)&servAddr, sizeof(servAddr));
	if(ret < 0)
	{
		perror("bind error!");
		close(sockFd);
		return -1;
	}
	printf("bind ok!\n");


	//创建监听队
	//socket从主动变成被动
	ret = listen(sockFd, 10);
	if(ret < 0)
	{
		perror("listen error!");
		close(sockFd);
		return -1;
	}
	printf("listening.......\n");



	//等待并建立连接
	struct sockaddr_in cliAddr = {0};
	socklen_t len = sizeof(cliAddr);
	int connFd = accept(sockFd, (struct sockaddr *)&cliAddr, &len);
	if(connFd < 0)
	{
		perror("accept error!");
		close(sockFd);
		return -1;
	}
	printf("IP: %s, PORT: %d accept ok!\n", inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port));

	pid_t pid = fork();
	char buf[100] = {0};
	if(pid < 0)
	{
		perror("fork error!");
		return -1;
	}
	else if(pid > 0)
	{

		//接收消息
		while(1)
		{
			memset(buf, 0, sizeof

你可能感兴趣的:(服务器,tcp/ip,网络)