c语言 - "Connected" UDP 套接字,双向通信?



如何在连接的 UDP 套接字上实现 2 路通信?

我可以从客户端发送到服务器,但无法从服务器获取消息。这是我的代码。我认为问题一定出在服务器端,但我不知道如何解决这个问题。我故意删除了错误检查,只是为了在SO上发布并保持我的帖子简短。我没有收到任何方面的任何错误。

我可以使用连接的UDP套接字运行该程序,但不能使用连接的套接字运行该程序。

服务器.c

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
int main()
{
  int sockfd;
  struct sockaddr_in me;
  char buffer[1024];
  sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  memset(&me, '', sizeof(me));
  me.sin_family = AF_INET;
  me.sin_port = htons(8080);
  me.sin_addr.s_addr = inet_addr("127.0.0.1");
  bind(sockfd, (struct sockaddr *)&me, sizeof(me));
  recv(sockfd, buffer, 1024, 0);
  printf("[+]Data Received: %sn", buffer);
  strcpy(buffer, "Hello Clientn");
  send(sockfd, buffer, 1024, 0);
  printf("[+]Data Send: %sn", buffer);
  return 0;
}

客户端.c

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
int main()
{
  int sockfd;
  struct sockaddr_in other;
  char buffer[1024];
  sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  memset(&other, '', sizeof(other));
  other.sin_family = AF_INET;
  other.sin_port = htons(8080);
  other.sin_addr.s_addr = inet_addr("127.0.0.1");
  connect(sockfd, (struct sockaddr *)&other, sizeof(other));
  strcpy(buffer, "Hello Servern");
  send(sockfd, buffer, 1024, 0);
  printf("[+]Data Send: %sn", buffer);
  recv(sockfd, buffer, 1024, 0);
  printf("[+]Data Received: %sn", buffer);
  return 0;
}

服务器输出

[+]Data Received: Hello Server
[+]Data Send: Hello Client

客户端输出

[+]Data Send: Hello Server
// Here it does not receive the message sent by server.

在 Linux 上,strace可执行文件,服务器发送确实是这样说的:

sendto(3, "Hello Clientn310$2204J177"...,
       1024, 0, NULL, 0) = -1 EDESTADDRREQ (Destination address required)

即服务器套接字确实不知道它需要发送到的地址。任何UDP 套接字必须通过connect ing或在 sendto 中提供目标套接字地址来知道套接字的另一端。 UDP 套接字上的connect意味着只需为 send 设置默认地址。


要在"服务器"端连接套接字,您应该使用recvfrom找出发送方的套接字地址 - 然后您可以使用该地址connect或继续使用 sendto .使用sendto同一个套接字可以同时与许多不同的方进行通信。


TCP 服务器/客户端套接字

是不同的情况,因为服务器端的侦听/接受会返回与原始服务器套接字不同的连接套接字。

最新更新