1. 程式人生 > >linux下socket程式設計“Broken pipe”錯誤

linux下socket程式設計“Broken pipe”錯誤

工作需要,對接伺服器的時候,客戶端傳送資料報錯“Broken pipe

原因是對一個已關閉的套接字write兩次

細節講解參考:https://www.cnblogs.com/jingzhishen/p/3453727.html

 

demo

客戶端程式碼:

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>

int main()
{
	int sockfd = 0;
	sockaddr_in addr = {0};
	char str[100] = "hello";

	sockfd = socket(AF_INET, SOCK_STREAM, 0);

	addr.sin_addr.s_addr = htons(INADDR_ANY);
	addr.sin_family = AF_INET;
	addr.sin_port = 6768;

	while (-1 == connect(sockfd, (sockaddr *)&addr, sizeof(addr)))
	{
		perror("connect err : ");
		sleep(1);
	}

	sleep(1);

	for (int i = 0; i < 2; i++)
	{
#if 1
		if (-1 == write(sockfd, str, strlen(str)))
		{
			perror("write err : ");
		}
#else		// read不會報錯
		if (0 > read(sockfd, str, sizeof(str)))
		{
			perror("read err : ");
		}
#endif
	}

	close(sockfd);

	printf("exit client\n");

	return 0;
}

伺服器端程式碼:

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>

int main()
{
	int sockfd = 0;
	sockaddr_in addr = {0};
	char str[100] = "hello";

	sockfd = socket(AF_INET, SOCK_STREAM, 0);

	addr.sin_addr.s_addr = htons(INADDR_ANY);
	addr.sin_family = AF_INET;
	addr.sin_port = 6768;

	while (-1 == connect(sockfd, (sockaddr *)&addr, sizeof(addr)))
	{
		perror("connect err : ");
		sleep(1);
	}

	sleep(1);

	for (int i = 0; i < 2; i++)
	{
#if 1
		if (-1 == write(sockfd, str, strlen(str)))
		{
			perror("write err : ");
		}
#else		// read不會報錯
		if (0 > read(sockfd, str, sizeof(str)))
		{
			perror("read err : ");
		}
#endif
	}

	close(sockfd);

	printf("exit client\n");

	return 0;
}