我正在用c ++设置一个Web服务器。我需要从服务器返回矢量形式的特征向量。我看到套接字不允许这样的对象直接通过,但需要序列化它。我试图通过将我的矢量结果转换为char * a来序列化它。但是当我做卷曲请求时,它仍然没有回复。 有人会告诉我这里的诀窍吗?
/* A simple server in the internet domain using TCP
The port number is passed as an argument */
// server.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <vector>
#include <iostream>
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
while (1 == 1) {
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("before result: %s\n",buffer);
std::vector<float> fv;
fv.push_back(7);
fv.push_back(8);
char* result = reinterpret_cast<char*>(&fv);
send(newsockfd, result, sizeof(result), 0);
//n = write(newsockfd,"I got your message",18);
//if (n < 0) error("ERROR writing to socket");
printf("message sent. \n");
close(newsockfd);
//close(sockfd);
}
return 0;
}
编译代码:
g++ -o server server.cpp
并运行:
./server 8080
对于卷曲请求:
curl http://localhost:8080
我得到了:
alliey:socket alliey$ curl http://localhost:8080
`N�.
我该如何解释回应?
答案 0 :(得分:0)
我想通过简单地发送原始数据来解决这个问题:
send(newsockfd, result.data(), sizeof(result[0])*result.size(), 0);
在客户端,我使用python struck.unpack来接收结果。它运作得很好。
但仍然感谢上面的所有提示!