server.c
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
#include <unistd.h>
int main() {
int s;
struct sockaddr_in server, client;
int c, l;
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
printf("Eroare la crearea socketului server\n");
return 1;
}
memset(&server, 0, sizeof(server));
server.sin_port = htons(1234);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
if (bind(s, (struct sockaddr *) &server, sizeof(server)) < 0) {
printf("Eroare la bind\n");
return 1;
}
listen(s, 5);
l = sizeof(client);
memset(&client, 0, sizeof(client));
while (1) {
int a, b, suma;
c = accept(s, (struct sockaddr *) &client, &l);
printf("S-a conectat un client.\n");
// deservirea clientului
recv(c, &a, sizeof(a), 0);
recv(c, &b, sizeof(b), 0);
a = ntohs(a);
b = ntohs(b);
suma = a + b;
suma = htons(suma);
send(c, &suma, sizeof(suma), 0);
close(c);
// sfarsitul deservirii clientului;
}
}
现在想法很简单:服务器应该收到2个数字,然后将结果发送回客户端。
client.py
import socket
import struct
import sys
def main():
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
client.connect(('localhost',1234))
except socket.error as error:
print('Connect error:',error)
exit(1)
a=int(input('a='))
b=int(input('b='))
try:
client.sendall(struct.pack('!i',a))
client.sendall(struct.pack('!i',b))
except socket.error as error:
print("Send error:",error)
exit(1)
try:
suma=client.recv(sys.getsizeof(int))
suma=struct.unpack('!i', suma)[0]
print("a + b =",suma)
except socket.error as error:
print("Receive error:",error)
exit(1)
if __name__ == '__main__':
main()
客户端在一个python服务器上正确地发送数字,至少我是这么认为的,它具有相同的功能,而奇怪的是c客户端与python服务器一起工作,但当我运行c服务器时python客户端,服务器接收a和b值为0.any ideas?
尝试使用如下所述的缓冲区,没有结果,仍然接收0。
另外,我忘了提到我检查了recv的值,确切地说是a和b的大小,没有recv错误。
答案 0 :(得分:1)
您的服务器在使用ntohs()
时会调用ntohl()
。 s
(对于“短”)版本以双字节整数运行。 l
(对于“long”)版本以四字节整数运行。
试试这个:
a = ntohl(a);
b = ntohl(b);
和
suma = htonl(suma);