C &引用;“已连接”;UDP套接字,双向通信?
如何在连接的UDP套接字上实现双向通信? 我可以从客户端向服务器发送消息,但无法从服务器获取消息。这是我的密码。我认为问题一定出在服务器端,但我不知道如何解决这个问题。我故意删除了错误检查,只是为了发布,所以我的帖子要简短。我没有收到任何方面的错误 我可以使用未连接的UDP套接字运行此程序,但不能使用已连接的套接字 Server.cC &引用;“已连接”;UDP套接字,双向通信?,c,sockets,networking,network-programming,udp,C,Sockets,Networking,Network Programming,Udp,如何在连接的UDP套接字上实现双向通信? 我可以从客户端向服务器发送消息,但无法从服务器获取消息。这是我的密码。我认为问题一定出在服务器端,但我不知道如何解决这个问题。我故意删除了错误检查,只是为了发布,所以我的帖子要简短。我没有收到任何方面的错误 我可以使用未连接的UDP套接字运行此程序,但不能使用已连接的套接字 Server.c #include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h>
#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, '\0', 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;
}
#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, '\0', 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 Send: Hello Server
// Here it does not receive the message sent by server.
在linux上,
strace
ing可执行文件时,服务器发送会这样说:
sendto(3, "Hello Client\n\0\0\0\310$\220\4J\177\0\0\0\0\0\0\0\0\0\0"...,
1024, 0, NULL, 0) = -1 EDESTADDRREQ (Destination address required)
i、 服务器套接字确实不知道它需要发送到的地址。任何UDP套接字都必须通过connect
ing或在sendto
中提供目标套接字地址来识别套接字的另一端。
UDP套接字上的连接意味着只需为发送设置默认地址
要将“服务器”端的套接字与未知方连接,您应该使用
recvfrom
查找发送方的套接字地址-然后您可以使用此地址connect
或继续使用sendto
。使用sendto
时,同一套接字可以同时与多个不同的方通信
TCP服务器/客户端套接字是另一种情况,因为服务器端的listen/accept返回一个与原始服务器套接字不同的新连接套接字。您没有检查任何这些系统调用的返回值。当两个套接字绑定到同一台机器上同一地址的同一端口时,您认为会发生什么情况?正如我所说的,我刚刚删除了这篇文章的错误检查。我已经在检查返回值和输出是否与我发布的相同。啊,事实上,我读到您有两个绑定。@AnttiHaapala如何解决这个问题。请指导我。不,问题是你删除了错误处理代码,所以我们不知道你是否有同样的错误。如何连接服务器端的套接字?@BhavinPanara更新。基本上,“连接”与您之前所说的工作机制没有什么不同。因此,我必须在服务器端的
recvfrom()
上接收第一条消息,然后我可以使用刚刚收到的地址调用服务器端的connect()
,然后只有我可以继续执行send()
&recv()
用于双方未来的通信。我说的对吗?@BhavinPanara yesOK。谢谢你提供的所有信息。
sendto(3, "Hello Client\n\0\0\0\310$\220\4J\177\0\0\0\0\0\0\0\0\0\0"...,
1024, 0, NULL, 0) = -1 EDESTADDRREQ (Destination address required)