1、服务器端
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
using namespace std;
void error_handling(const char* message);
int main(int argc, char **argv)
{
if (argc != 2)
{
cout << "Usage: " << argv[0] << " <port>" << endl;
exit(1);
}
int server_socket = socket(PF_INET, SOCK_STREAM, 0); //获得服务器socket资源
if (server_socket == -1)
{
error_handling("socket() error");
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[1]));
if (bind(server_socket, (const struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) // 为socket分配ip和端口号
{
error_handling("bind() error");
}
if (listen(server_socket, 5) == -1) // 将socket置为可连接状态
{
error_handling("listen() error");
}
while (true)
{
struct sockaddr_in client_addr;
socklen_t client_addr_size = sizeof(client_addr);
int client_socket = accept(server_socket, (struct sockaddr*)(&client_addr), &client_addr_size); // 受理连接请求
if (client_socket == -1)
{
error_handling("accept() error");
}
const string message{"Hello World!"};
write(client_socket, message.data(), message.size()); //传输数据给客户端
close(client_socket); //关闭客户端socket资源
}
close(server_socket); //关闭服务器端socket资源
return 0;
}
void error_handling(const char* message)
{
cout << message << endl;
exit(1);
}
2、客户端实现
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstdlib>
using namespace std;
void error_handling(const char* message);
int main(int argc, char **argv)
{
if (argc != 3)
{
cout << "Usage: " << argv[0] << " <IP> <port>" << endl;
exit(1);
}
int client_socket = socket(PF_INET, SOCK_STREAM, 0); //创建客户端socket资源
if (client_socket == -1)
{
error_handling("socket() error");
exit(1);
}
// 设置要连接的服务器地址
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons(atoi(argv[2]));
if (connect(client_socket, (const struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) //连接服务器
{
error_handling("connect() error");
exit(1);
}
char message[30];
int msg_size = read(client_socket, message, sizeof(message) - 1); //向服务器发送请求
if (msg_size == -1)
{
error_handling("read() error");
exit(1);
}
cout << "Message from server: " << message << endl;
close(client_socket); //关闭socket
return 0;
}
void error_handling(const char* message)
{
cout << message << endl;
}