如何从某个客户端读取输入数据,然后使用该数据进行计算,然后将结果写回客户端。我现在所拥有的将输入数据,但当我回写我的客户端程序似乎没有得到任何东西。继承人我现在所拥有的。它不是整个代码,但任何未定义的变量应具有明确的含义。我是否需要制作一个writefd并检查一下?我需要确保它回到正确的客户端并且不了解如何执行此操作?
(?<={{).*?(?=}})
答案 0 :(得分:0)
当master_socket
被标记为可读时,您正在recv()
上呼叫new_socket
。假设master_socket
是您的侦听服务器套接字,则需要调用accept()
来接收新客户端。除非recv()
告诉您特定客户端是可读的,然后从该客户端读取,否则不要致电select()
。
尝试更像这样的东西:
for (i = 0; i < max_clients; ++i)
client_socket[i] = -1;
...
while (TRUE)
{
FD_ZERO(&readfds);
//add master socket to set
FD_SET(master_socket, &readfds);
max_sd = master_socket;
//add child sockets to set
for (i = 0; i < max_clients; ++i)
{
//socket descriptor
sd = client_socket[i];
if (sd > -1)
{
FD_SET(sd, &readfds);
if (sd > max_sd)
max_sd = sd;
}
}
//waiting for activity
activity = select(max_sd + 1, &readfds, NULL, NULL, NULL);
if (activity < 0)
{
if (errno != EINTR)
printf("select error");
}
else
{
//check master socket to accept from
if (FD_ISSET(master_socket, &readfds))
{
new_socket = accept(master_socket, NULL, NULL);
if (new_socket < 0)
{
printf("accept error");
}
else
{
//add new socket to array of sockets
for (i = 0; i < max_clients; ++i)
{
//if position is empty
if (client_socket[i] == -1)
{
client_socket[i] = new_socket;
printf("Adding to list of sockets as %d\n" , i);
send(new_socket, "here", strlen("here"), 0);
new_socket = -1;
break;
}
}
// close new socket if no room for it
if (new_socket > -1)
close(new_socket);
}
}
//check child sockets to read from
for (i = 0 ; i < max_clients; ++i)
{
sd = client_socket[i];
if (sd > -1)
{
if (FD_ISSET(sd, &readfds))
{
len = recv(sd, buffer, 1025, 0);
if (len > 0)
{
// data received
buffer[len] = 0; // make sure it is null terminated
printf("data: %s", buffer);
// or: printf("data: %.*s", len, buffer);
}
else
{
if (len == 0)
printf("disconnected");
else
printf("recv error");
printf("Removing from list of sockets at %d\n", i);
close(sd);
client_socket[i] = -1;
}
}
}
}
}