我的服务器没有从客户端收到任何数据,但没有错误,所以我真的不知道出了什么问题。在客户端的while循环中,我尝试发送消息。服务器保留在recvfrom函数中,似乎没有数据。 cmd中的netstat显示服务器侦听端口50000.我向客户端提供带有控制台参数的IPv6地址:: 1。
以下是服务器的代码:
#include <WinSock2.h>
#include <ws2ipdef.h>
#include <stdio.h>
#define PORT 50000
#define BUFFERSIZE 64
void error(char *err)
{
fprintf(stderr,"%s: %d\n", err, WSAGetLastError());
getchar();
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
struct sockaddr_in6 server, client;
SOCKET sock;
char buffer[BUFFERSIZE];
LPTSTR recvBuff[1024];
DWORD recvBuffLen = 1024UL;
int len = sizeof(client);
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(1,1);
WSAStartup(wVersionRequested, &wsaData);
sock = socket(AF_INET6, SOCK_DGRAM, 0);
if (sock < 0)
error("Fehler beim Anlegen des Sockets");
memset( &server, 0, sizeof (server));
memset( &client, 0, sizeof (client));
server.sin6_family = AF_INET6;
server.sin6_port = htons(PORT);
server.sin6_addr = in6addr_any;
if (bind(sock, (struct sockaddr *) &server, sizeof(server)) == -1)
error("Fehler beim binden des Sockets");
while (1)
{
if (recvfrom(sock, buffer, BUFFERSIZE, 0, (struct sockaddr *)&client, &len) == -1)
error("Fehler beim erhalten von Daten");
printf("...");
printf("Pakete erhalten von: %s:%d\nDaten: %s\n\n", WSAAddressToString((struct sockaddr *)&client.sin6_addr, len, NULL, *recvBuff, &recvBuffLen), PORT, buffer);
}
closesocket(sock);
return 0;
}
这里是我客户的代码:
#include <WinSock2.h>
#include <ws2ipdef.h>
#include <stdio.h>
#define PORT 50000
#define BUFFERSIZE 64
void error(char *err)
{
fprintf(stderr,"%s: %d\n", err, WSAGetLastError());
getchar();
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
struct sockaddr_in6 server;
SOCKET sock;
char buffer[BUFFERSIZE];
int len = sizeof(server);
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(1,1);
WSAStartup(wVersionRequested, &wsaData);
if (argc != 2) {
printf("Usage: %s <Server-IP>\n", argv[0]);
getchar();
exit(0);
}
sock = socket(AF_INET6, SOCK_DGRAM, 0);
if (sock == -1)
error("Socket Fehler");
memset( &server, 0, sizeof (server));
server.sin6_family = AF_INET6;
server.sin6_port = htons(PORT);
if ((WSAStringToAddressA(argv[1], AF_INET6, NULL, (SOCKADDR *)&server, &len)) < 0)
error("String konnte nicht aufgelößt werden");
while (1)
{
printf("\nDaten eingeben: (Enter für Text bestätigen, 'q' eingeben um zu beenden)");
scanf("%[^\n]", buffer);
getchar();
if (strcmp(buffer, "q") == 0)
exit(0);
if (sendto(sock, buffer, BUFFERSIZE, 0, (struct sockaddr *)&server, len) == -1)
error("Fehler bei Übertragung");
}
closesocket(sock);
return 0;
}
我希望有人可以提供帮助。
答案 0 :(得分:0)
只是一个猜测:问题可能是stdout
缓冲 - 尝试使用
setbuf(stdout, NULL);
或只是在stdout
:
printf()
printf("...");
printf("Pakete erhalten von: %s:%d\nDaten: %s\n\n", WSAAddressToString((struct sockaddr *)&client.sin6_addr, len, NULL, *recvBuff, &recvBuffLen), PORT, buffer);
fflush(stdout);