我无法将数据发送到服务器C ++ 11

时间:2019-04-12 10:38:33

标签: sockets c++11 server client

我是套接字编程级别的初学者,所以我发现了一些可能很简单的问题。我试图从客户端向服务器发送一条简单的消息,但是命令send return (-1)就是服务器未收到该消息的原因。

另外,我在服务器代码和接收器命令中也遇到相同的问题。 return (-1)

以下是我的客户代码:

bool ClientSock() {
int sock;
struct sockaddr_in address;

sock = socket(AF_INET, SOCK_STREAM, 0);
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_family = AF_INET;
address.sin_port = htons(10102);



if (connect(sock, (struct sockaddr*) &address, sizeof (address)) < 0) {
    cout << "connect failed. Error \n";
    return 0 ;
} else
    return 1;
}

void SendComm() {

long ok;
    char MESSAGE [2000];
    string msg;
    cout << "enter message:\t";
    cin>> msg;
    const char * s = msg.c_str();
    int sock;
    ok = send(sock, s, 1024, 0);`enter code here`
    if ( send(sock,s,1024,0)< 0){//this is the problem
    std::cout << "you can not send the message";
}
    else{
    ok = recv(sock, MESSAGE, sizeof (MESSAGE), 0);
    string reply;
    reply = MESSAGE;
    cout << "server says:_t" << reply << endl;
}
}

int main() {
if (ClientSock()==1){
     SendComm();
}
else 
    std::cout << "error";

 }

这是我的服务器代码:

bool initialize() {
int conSock;
int ListenSock;
socklen_t addrsize;
struct sockaddr_in address;
addrsize = sizeof (address);

conSock = socket(AF_INET, SOCK_STREAM, 0);
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_family = AF_INET;
address.sin_port = htons(10102);
ListenSock = socket(AF_INET, SOCK_STREAM, 0);
bind(ListenSock, (sockaddr *) & address, sizeof (address));
listen(ListenSock, SOMAXCONN);

std::cout << "server waiting for connexion\n\n ";


if (conSock = accept(ListenSock, (struct sockaddr *) &address, &addrsize) < 0) {
    cout << "connect failed. Error";
    return 0;
} else
    return 1;
}

void Communicate() {

int conSock;
int ListenSock;
struct sockaddr_in address;
socklen_t addrsize;

long ok;
char MESSAGE[2000];
ok = recv(conSock, MESSAGE, sizeof (MESSAGE), 0);
if (recv(conSock, MESSAGE, sizeof (MESSAGE), 0)< 0){
    std:: cout << "No message" ;  
}
else{
string msg;
msg = MESSAGE;
cout << " client says:\t" << msg << endl;
string reply;
cout << "enter reply:\t";
cin>> reply;
const char* s = reply.c_str();
ok = send(conSock, s, 1024, 0);
}}

int main() {

if (initialize() == 1) {
   Communicate();

} else
    std::cout << "error ";
}

0 个答案:

没有答案