在这里,我尝试使用 send() 方法将字符串发送到函数参数并作为套接字中的参数。
user_main.cpp
int main(int argc, char *argv[] )
{
const char *buffer;
const char *ch;
std::string input = argv[2];
int ar[2];
printf("Client : \n");
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
printf( "\n%s filename\n", argv[0] );
}
else
{
ch=client(input);
ar[0]=((int*)ch)[0];
ar[1]=((int*)ch)[1];
}
printf("\n @ar[0]=%d;ar[1]=%d@ \n",ar[0],ar[1]);
return ar[1];
}
客户端.cpp:
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <netinet/in.h>
#include <resolv.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#pragma GCC diagnostic ignored "-Wwrite-strings"
int ar[10];
char *client(std::string input_string)
{
//Process user inserted data. Remove punctuation marks from input_string
std::replace_if(input_string.begin(), input_string.end(),
std::ptr_fun<int, int>(&std::ispunct), ' ');
int host_port= 1103;
char* host_name="127.0.0.1";
struct sockaddr_in my_addr;
int bytecount;
int buffer_len=0;
int i=0,x=0;
int hsock;
int * p_int;
int err;
hsock = socket(AF_INET, SOCK_STREAM, 0);
if(hsock == -1){
printf("Error initializing socket %d\n",errno);
goto FINISH;
}
p_int = (int*)malloc(sizeof(int));
*p_int = 1;
if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
(setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){
printf("Error setting options %d\n",errno);
free(p_int);
goto FINISH;
}
free(p_int);
my_addr.sin_family = AF_INET ; my_addr.sin_port = htons(host_port);
memset(&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr = inet_addr(host_name);
if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ){
if((err = errno) != EINPROGRESS){
fprintf(stderr, "Error connecting socket %d\n", errno);
goto FINISH;
}
}
if( (bytecount=send(hsock, input_string.c_str(), input_string.length(),0))== -1){
fprintf(stderr, "Error sending data %d\n", errno);
goto FINISH;
}
if((bytecount = recv(hsock, ar, sizeof(ar), 0))== -1){
fprintf(stderr, "Error receiving data %d\n", errno);
goto FINISH;
}
x= sizeof(ar)/sizeof(int);
printf("x is %d: \n ",x);
for(i=0; i < (sizeof(ar)/sizeof(*ar));i++)
{
std::cout << ar[i] << std::endl;
}
close(hsock);
FINISH:
;
//printf("array item2 %d \n",ar[1]);
return (char *)ar;
}
客户端.h
#include <iostream>
#ifndef client_h__
#define client_h__
extern char *client(std::string string_input);
#endif
它编译正确,但是当我运行它时出现错误:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
Aborted (core dumped)
我看到了这个错误的解决方案:解决方案。但是在这里,我无处使用 const char* 值 NULL 调用 std::string 构造函数。或者我不知道。请让我知道我在哪里犯错。