我有一个服务器,它联系另一个服务器以检索客户端请求的文件。
请求流程为:
Client ----> Server A ----> Server B
发送文件的过程:
Server B ---> server A ----> client
我无法将客户端直接连接到服务器B。
要求:
服务器 A 必须在客户端文件数据到达另一台服务器时将其转发给客户端(无需等待整个文件的接收)。因此,它们到达时是逐字节的。
其他信息:
TCP socket;
Programming in C on Linux.
有人可以给我一些实现这个的想法吗?
更新
这是我的第一次尝试:
/* This code is refered to SERVER A */
/* s is the file descriptor for comunicate with SERVER B */
/* t is the file descriptor for comunicate with CLIENT */
int forward (int s, int t, char *buffer, size_t bytes){
size_t n;
ssize_t nread;
ssize_t nsend;
char c;
for (n=1; n<bytes; n++)
{
nread=recv(s, &c, 1, 0);
if (nread == 1)
{
nsend = send(t,c,1,0);
if (nsend<=0) {
return (-1);
}
}
else if (nread == 0)
{
return (n-1); /* Errore */
}
else
return (-1); /* Errore */
}
return (n);
}
最佳答案
*首先服务器B应该监听80端口的http连接。(我们可以在这里使用xampp来创建服务器)。
服务器A(充当代理)应该在特定端口监听tcp连接,一旦它在该端口收到客户端的任何请求。首先它与客户端连接,然后将请求传输到服务器B dst-port 80 通过建立 tcp 连接并等待服务器 B 的回复。
当服务器B收到请求后,将数据转发给服务器A,然后服务器A转发给客户端。
要建立tcp连接,可以引用beej指南的socket编程。这里给出了一个简单的实现。 对于一次多个连接,您可以使用 Pthreads 创建线程,也可以使用 fork() 系统调用创建进程。*
关于c - 使用 TCP 套接字发送字节到字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17084841/