了解基于TCP/IP协议的Socket客户端程序编写(Python/C/C++)。
时间: 2024-12-25 10:31:02 浏览: 5
基于TCP/IP协议的Socket编程是一种网络通信的基础技术,用于创建应用程序间的连接。以下是使用Python、C和C++分别编写Socket客户端的基本步骤:
**Python**:
```python
import socket
def client():
# 创建socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务器
server_address = ('localhost', 12345) # 服务器地址和端口
sock.connect(server_address)
# 发送数据
message = 'Hello, Server!'
sock.sendall(message.encode('utf-8'))
# 接收响应
response = sock.recv(1024).decode('utf-8')
print(f'Received: {response}')
# 关闭连接
sock.close()
if __name__ == '__main__':
client()
```
**C** (使用POSIX sockets):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(12345); // 端口号
inet_pton(AF_INET, "localhost", &server_addr.sin_addr);
connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
char message[] = "Hello, Server!";
send(sock, message, strlen(message), 0);
char buffer[1024];
recv(sock, buffer, sizeof(buffer), 0);
printf("Received: %s\n", buffer);
close(sock);
return 0;
}
```
**C++**:
```cpp
#include <iostream>
#include <boost/asio.hpp>
int main() {
try {
boost::asio::io_context io_context;
boost::asio::ip::tcp::socket socket(io_context);
boost::asio::ip::tcp::resolver resolver(io_context);
boost::asio::ip::tcp::resolver::query query("localhost", "12345");
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
socket.connect(*endpoint_iterator);
std::string message = "Hello, Server!";
boost::asio::write(socket, boost::asio::buffer(message));
boost::array<char, 1024> receive_buffer;
boost::asio::read(socket, boost::asio::dynamic_buffer(receive_buffer));
std::cout << "Received: " << std::string(receive_buffer.data(), receive_buffer.size()) << std::endl;
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
```
阅读全文