如果数据是从另一台计算机“发送”的,那么如何将我的套接字例程设置为“发送”(第一个)或“切换”为“接收”?
感谢
一般代码:
-(void) TcpClient{
char buffer[128];
struct sockaddr_in sin;
struct hostent *host;
int s;
host = gethostbyname("10.0.0.3");
memcpy(&(sin.sin_addr), host->h_addr,host->h_length);
sin.sin_family = host->h_addrtype;
sin.sin_port = htons(4000);
s = socket(AF_INET, SOCK_STREAM, 0);
connect(s, (struct sockaddr*)&sin, sizeof(sin));
while(1){//this is the Client sequence:
send(s, buffer, strlen(buffer), 0);//but what if the Server sends first ?? Client needs to receive here first
recv(s, buffer, sizeof(buffer), 0);
}
close(s);
}
答案 0 :(得分:2)
套接字是双向的。它可以随时读取和写入。如果要编写决定何时读取和何时写入的单个例程,则需要使用select()
函数。它将告诉您套接字何时可以读取数据,以及套接字何时可以接受要发送的数据。如果套接字在您要发送数据之前接收数据,则例程可以检测到该数据并执行“接收/发送”操作。如果在套接字接收数据之前有数据要发送,则例程可以检测到并执行“发送/接收”操作。例如:
while (1)
{
fd_set fd;
FD_ZERO(&fd);
FD_SET(s, &fd);
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
int ret;
if (select(s+1, &fd, NULL, NULL, &tv) > 0)
{
ret = recv(s, buffer, sizeof(buffer), 0);
if (ret > 0)
send(s, buffer, ret, 0);
}
else
{
ret = send(s, buffer, strlen(buffer), 0);
if (ret > 0)
recv(s, buffer, ret, 0);
}
}
答案 1 :(得分:1)