在 Ubuntu 下進行 C++ 網絡編程實戰,你需要了解一些基本的網絡編程概念和相關庫
sudo apt-get update
sudo apt-get install build-essential g++ cmake
mkdir cpp_networking_project
cd cpp_networking_project
CMakeLists.txt
的文件,用于配置項目:cmake_minimum_required(VERSION 3.10)
project(cpp_networking_project)
set(CMAKE_CXX_STANDARD 14)
add_executable(server server.cpp)
add_executable(client client.cpp)
server.cpp
:
#include<iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
const int PORT = 8080;
const int BUFFER_SIZE = 1024;
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
char *message = "Hello from server!";
// 創建 socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
std::cerr << "Socket creation failed"<< std::endl;
return -1;
}
// 綁定 socket
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
std::cerr << "Bind failed"<< std::endl;
return -1;
}
// 監聽連接
if (listen(server_fd, 3) < 0) {
std::cerr << "Listen failed"<< std::endl;
return -1;
}
// 接受連接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
std::cerr << "Accept failed"<< std::endl;
return -1;
}
// 讀取客戶端發送的數據
read(new_socket, buffer, BUFFER_SIZE);
std::cout << "Message from client: "<< buffer<< std::endl;
// 向客戶端發送消息
send(new_socket, message, strlen(message), 0);
std::cout << "Message sent to client"<< std::endl;
// 關閉 socket
close(new_socket);
close(server_fd);
return 0;
}
client.cpp
:
#include<iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
const std::string SERVER_IP = "127.0.0.1";
const int PORT = 8080;
const int BUFFER_SIZE = 1024;
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
char buffer[BUFFER_SIZE] = {0};
char *message = "Hello from client!";
// 創建 socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
std::cerr << "Socket creation failed"<< std::endl;
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// 將 IP 地址轉換為二進制格式
if (inet_pton(AF_INET, SERVER_IP.c_str(), &serv_addr.sin_addr) <= 0) {
std::cerr << "Invalid address / Address not supported"<< std::endl;
return -1;
}
// 連接到服務器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
std::cerr << "Connection failed"<< std::endl;
return -1;
}
// 向服務器發送消息
send(sock, message, strlen(message), 0);
// 從服務器接收消息
read(sock, buffer, BUFFER_SIZE);
std::cout << "Message from server: "<< buffer<< std::endl;
// 關閉 socket
close(sock);
return 0;
}
cmake .
make
./server &
./client
這個例子展示了如何在 Ubuntu 下使用 C++ 進行基本的網絡編程。你可以根據自己的需求修改代碼,實現更復雜的功能。