gpt4 book ai didi

c++ - 发送和接收 C++

转载 作者:行者123 更新时间:2023-11-28 05:53:36 27 4
gpt4 key购买 nike

我正在尝试在我的程序中使用发送和接收命令,这是一个客户端服务器消息传递软件。

然而,当代码运行时,我似乎无法传递消息,因为 send cmd 没有传递数据。命令执行后,我尝试传递的数据(缓冲区)为空,我通过打印(缓冲区)进行了检查。为什么会这样……如果有人能帮助我,我将不胜感激。

服务器端代码:

#include<iostream>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<netinet/ip.h>
using namespace std;

int main()
{
int client, server, i;
int portNum = 1500;
bool isExit = false;
int bufsize = 1024;
char buffer[bufsize];

struct sockaddr_in server_addr;
socklen_t size;

// init socket

client = socket(AF_INET, SOCK_STREAM, 0);

if (client < 0)
{
cout << "Error establishing connection" << endl;
exit(1);
}

cout << "Server Socket connection created..." << endl;

server_addr.sin_family = AF_INET;
// server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_port = htons(portNum);
server_addr.sin_addr.s_addr = inet_addr("192.168.0.5");
// Binding socket

if (bind(client, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0)
{
cout << "Error binding socket...." << endl;
exit(1);
}

size = sizeof(server_addr);
cout << "Looking for clients..." << endl;

// Listening socket

listen(client, 1);

// Accept client

server = accept(client, (struct sockaddr*)&server_addr, &size);
if (server < 0)
{
cout << "Error on accepting.." << endl;
exit(1);
}
cout << "Connected with client..." << endl;
cout << "Enter your message:\n" << endl;
cin >> buffer;
cout << buffer;
send(server, buffer, bufsize, 0);
cout << "message sent...\n", buffer;
return 0;
}

客户端代码

#include<iostream>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<netdb.h>

using namespace std;

int main()
{

int client, server, i;
int portNum = 1500;
bool isExit = false;
int bufsize = 1024;
char buffer[bufsize];
struct sockaddr_in server_addr;

// Init socket


client = socket(AF_INET, SOCK_STREAM, 0);

if (client < 0)
{
cout << "Error creating socket" << endl;
exit(1);
}

cout << "Client socket created" << endl;

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(portNum);
server_addr.sin_addr.s_addr = inet_addr("192.168.0.5");
// Connecting socket server

if (connect(client, (struct sockaddr*)&server_addr, sizeof(server_addr)) == 0)

{
cout << "Connecting to server..." << endl;
recv(client, buffer, bufsize, 0);

buffer[bufsize] = '\0';

cout << "client: received", buffer;

close(client);
}
return 0;
}

最佳答案

你实际上并没有打印 buffer :

cout << "client: received", buffer;

应该是:

cout << "client: received " << buffer;

你可能还想要一个 endl :

cout << "client: received " << buffer << endl;

关于c++ - 发送和接收 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34677667/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com