我试图在我的程序中使用send和recv命令,这是一个客户端服务器消息传递软件。
但是,似乎当代码运行时我无法传递消息,因为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;
}
答案 0 :(得分:1)
您实际上并未打印buffer
:
cout << "client: received", buffer;
应该是:
cout << "client: received " << buffer;
您可能还需要endl
:
cout << "client: received " << buffer << endl;