我在下面C
编写了这个简单的客户端服务器。客户端向服务器发送2个号码,服务器将2个号码的总和发送回客户端。我的问题是从服务器发送回客户端的总和,我不明白为什么它不起作用。它没有给出任何错误,只是receivedData
变量没有填充所需的int
。客户端成功发送带有2个号码的数据包到服务器,服务器成功接收到它们。
请注意,这只是一个教学示例,我没有使用线程来处理客户端。它只是一个客户端和一个服务器。
这是服务器:
// SERVER
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <signal.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#define PORT 2012
struct Packet
{
int a;
int b;
};
int main()
{
struct sockaddr_in clientAddress;
int sd;
if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("Error creating socketsss\n");
}
memset(&clientAddress, 0, sizeof(clientAddress));
clientAddress.sin_family = AF_INET;
clientAddress.sin_port = htons(PORT);
clientAddress.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sd, (struct sockaddr*)&clientAddress, sizeof(clientAddress)) < 0)
{
printf("Bind error\n");
}
if(listen(sd, 5) < 0)
{
printf("Listen error\n");
}
unsigned int len = 0;
int fd = accept(sd, (struct sockaddr*)&clientAddress, &len);
struct Packet received;
if(recv(fd, &received, sizeof(struct Packet), 0) < 0)
{
printf("Receive error");
}
int sum = received.a + received.b;
printf("Numarul ce trebui trimis este %d\n", sum);
if(send(sd, &sum, sizeof(sum), 0) < 0)
{
printf("Error sending data\n");
}
return 0;
}
这是客户:
// CLIENT
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SERVER_IP "127.0.0.1"
#define PORT 2012
struct Packet
{
int a;
int b;
};
int main()
{
struct sockaddr_in serverAddress;
int sd;
if((sd = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("Error creating socket\n");
}
memset((char *)&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr(SERVER_IP);
serverAddress.sin_port = htons(PORT);
if ((connect(sd,(struct sockaddr *)&serverAddress, sizeof(serverAddress))) < 0)
{
printf("Error connectiong to server!\n");
}
struct Packet packToSend;
packToSend.a = 14;
packToSend.b = 21;
if(send(sd, &packToSend, sizeof(packToSend), 0) < 0)
{
printf("Error sending data\n");
}
int receivedData = 0;
if(recv(sd, &receivedData, sizeof(int), 0) < 0)
{
printf("Receive error\n");
}
printf("I received %d \n", receivedData);
return 0;
}
谢谢!
答案 0 :(得分:2)
您正在发送侦听套接字,而不是您接受的套接字。