我有一个客户端从服务器A请求数据(DA),然后我需要将DA发送到第二个服务器B。在数据不大于缓冲区的情况下,我得到了它。但是以下内容不适用于将所有数据从A传递到B。我注意到,当我创建socket_fwd并在关闭第一个sockfd之后进行连接时,它可以工作。但是由于我需要转发所有数据,因此我需要在到达所有数据后立即对其进行处理
int sockfd, sockfd_fwd, n, n_fwd;
gint BUFFER=900;
char buf[BUFFER];
char* addr = "11.0.0.20"; //Server A listening on port 80
struct sockaddr_in server_addr = {0};
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(80);
char chunk[BUFFER];
gint nfw;
gint total_recv = 0;
gint total_fwd = 0;
struct sockaddr_in server_addr2 = {0};
server_addr2.sin_port = htons(5555);
server_addr2.sin_family = AF_INET;
char *addr2 = "127.0.0.1"; //Server B listening on port 555
//#################Request data from A:80 ###########################
if(inet_pton(AF_INET, addr, &server_addr.sin_addr) != 1){
perror("inet_pton");
return -1;
}
sockfd = socket(AF_INET, (SOCK_STREAM), 0); //socket with server A
if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0)
mylog(G_LOG_LEVEL_MESSAGE, __FUNCTION__,"Error on connect");
send(sockfd, buffer, strlen(buffer), 0); //Buffer contains something like get xx Kib to the server
bzero(buffer, BUFFER);
if(inet_pton(AF_INET, addr2, &server_addr2.sin_addr) != 1){
mylog(G_LOG_LEVEL_MESSAGE, __FUNCTION__,"Error inet pton");
return -1;
}
if(inet_pton(AF_INET, addr2, &server_addr2.sin_addr) != 1){
perror("inet_pton");
return -1;
}
sockfd_fwd = socket(AF_INET, (SOCK_STREAM), 0); //socket with server B
if (connect(sockfd_fwd, (struct sockaddr*)&server_addr2, sizeof(server_addr2)) < 0)
mylog(G_LOG_LEVEL_MESSAGE, __FUNCTION__,"Error on connect");
while ((n = recv(sockfd, chunk, BUFFER, 0)) > 0) {
total_recv += n;
mylog(G_LOG_LEVEL_MESSAGE, __FUNCTION__,"Recv chunk %s num-bytes:%i",chunk,total_recv);
nfw = send(sockfd_fwd, chunk ,n, 0);
memset(chunk,0,BUFFER);
}
close(sockfd);
close(sockfd_fwd);