c socket:同时接收和发送数据 [英] c socket: recv and send data simultaneously

查看:802
本文介绍了c socket:同时接收和发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多个客户端连接的客户端服务器聊天程序的客户端实现中遇到问题.问题是我遇到的问题是我应该如何同时发送(向另一个客户端聊天消息)和接收(从另一个客户端聊天消息)?发生的事情是我一直在发送数据,而从未读取.我是否需要进行分叉,并进行一次读取,而另一方进行发送?

I'm having issues with my client side implementation of client server chat program where multiple clients connect. The issue is that i'm coming across is that how exactly should i be sending (chat message to another client) and receiving (chat message from another client) at the same time? What's happening is that i'm always sending data and never reading. Do i need to fork and have one read and the other send?

这是相关代码

客户端

while(1) {

  fd_set rfds, wfds;
  FD_ZERO(&rfds);
  FD_ZERO(&wfds);

  FD_SET(serverSocket, &rfds);
  FD_SET(serverSocket, &wfds);

  if(select(serverSocket+1, &rfds, &wfds, NULL, NULL) < 0) {
      perror("select");
      exit(-1);
  }

  if (FD_ISSET(serverSocket, &rfds)) {
     // we got data, read it
  }
  if (FD_ISSET(serverSocket, &wfds)) {
     printf(">");

     // read keyboard
     sendLen = 0;
     while ((cmd[sendLen] = getchar()) != '\n')
        sendLen++;
     cmd[sendLen] = '\0';

     // send the data
  }
}

推荐答案

您还应将文件描述符0(标准输入)也放入select中,然后读取字符并对其进行缓冲,并且当套接字可用于写入时,复制整个缓冲区.这样,您就可以一直阻止标准输入的读取.

You should put the file descriptor 0 (standard input) in the select as well, then read chars and buffer them, and when the socket is available for writing, copy the entire buffer on it. In this way you just block reading on the standard input all the time.

添加

FD_SET(0, &rfds);

因此,当用户键入内容时,select也会返回.

so select will return when user types something as well.

还必须使用fcntl将stdin设置为非阻塞. 然后每次select都会告诉您stdin上的数据是这样的:

you must also use fcntl to set stdin as non-blocking. Then everytime select tells you there's data on stdin do something like that:

while(read(0,buffer+filled,1)>0) {}

如果缓冲区已满,请确保设置其他条件退出循环.

Make sure to put another condition to exit the loop if the buffer is full.

然后,当您可以在套接字上进行写操作时,执行发送,该发送的大小等于缓冲区中字节的大小,检查是否已全部写入,或将剩余的字节移到缓冲区的开头.

then when you can write on the socket do a send, of the size of the amount of bytes you have in your buffer, check if all of it has been written, or move the leftovers bytes at the beginning of the buffer.

(getchar())阻止了您,阻止您接收任何消息.

That while(getchar()) is blocking you preventing you from receving any messages.

这篇关于c socket:同时接收和发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆