"Connected" UDP套接字,双向通信?

"Connected" UDP sockets, communication in both directions?

如何在 连接的 UDP 套接字上实现双向通信?

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

我可以得到这个程序 运行 未连接 UDP 套接字,但不能使用 已连接 套接字。

Server.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, '[=11=]', 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: %s\n", buffer);

  strcpy(buffer, "Hello Client\n");
  send(sockfd, buffer, 1024, 0);
  printf("[+]Data Send: %s\n", buffer);

  return 0;
}

Client.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, '[=12=]', 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 Server\n");
  send(sockfd, buffer, 1024, 0);
  printf("[+]Data Send: %s\n", buffer);

  recv(sockfd, buffer, 1024, 0);
  printf("[+]Data Received: %s\n", 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、straceing 可执行文件时,服务器发送确实是这样说的:

sendto(3, "Hello Client\n[=10=][=10=][=10=]0$0J7[=10=][=10=][=10=][=10=][=10=][=10=][=10=][=10=][=10=][=10=]"...,
       1024, 0, NULL, 0) = -1 EDESTADDRREQ (Destination address required)

即服务器套接字确实不知道它需要发送到的地址。 任何 UDP套接字必须通过connecting、在[=中提供目标套接字地址使套接字的另一端已知13=]。 connect 在 UDP 套接字上意味着只需为 send.

设置默认地址

要连接 "server" 端的套接字,与未知方您应该使用 recvfrom 找出发送方的套接字地址 - 然后您可以 connect 使用此地址或继续使用 sendto。使用 sendto 同一个套接字可以同时与许多不同的方通信。


TCP server/client 套接字是不同的情况,因为 listen/accept 在服务器端 returns a new 连接的套接字与原始服务器套接字不同。