C++ 实现 TCP 协议
使用 C++ 实现 TCP 协议需要使用 Windows 套接字 API。以下是一个简单的 C++ 示例代码,使用套接字 API 创建 TCP 客户端程序:
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData
SOCKET ConnectSocket = INVALID_SOCKET
struct addrinfo *result = NULL, *ptr = NULL, hints
int iResult
// 初始化 Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData)
if (iResult != 0) {
std::cout <<"WSAStartup failed: " <<iResult <<std::endl
return 1
}
ZeroMemory(&hints, sizeof(hints))
hints.ai_family = AF_UNSPEC
hints.ai_socktype = SOCK_STREAM
hints.ai_protocol = IPPROTO_TCP
// 解析服务器地址和端口
iResult = getaddrinfo("www.example.com", "80", &hints, &result)
if (iResult != 0) {
std::cout <<"getaddrinfo failed: " <<iResult <<std::endl
WSACleanup()
return 1
}
// 创建套接字并连接服务器
for (ptr = resultptr != NULLptr = ptr->ai_next) {
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)
if (ConnectSocket == INVALID_SOCKET) {
std::cout <<"socket failed: " <<WSAGetLastError() <<std::endl
WSACleanup()
return 1
}
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen)
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket)
ConnectSocket = INVALID_SOCKET
continue
}
break
}
freeaddrinfo(result)
if (ConnectSocket == INVALID_SOCKET) {
std::cout <<"Unable to connect to server" <<std::endl
WSACleanup()
return 1
}
// 发送和接收数据
iResult = send(ConnectSocket, "GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"), 0)
if (iResult == SOCKET_ERROR) {
std::cout <<"send failed: " <<WSAGetLastError() <<std::endl
closesocket(ConnectSocket)
WSACleanup()
return 1
}
char recvbuf[512]
do {
iResult = recv(ConnectSocket, recvbuf, sizeof(recvbuf), 0)
if (iResult >0) {
std::cout.write(recvbuf, iResult)
}
else if (iResult == 0) {
std::cout <<"Connection closed" <<std::endl
}
else {
std::cout <<"recv failed: " <<WSAGetLastError() <<std::endl
}
} while (iResult >0)
// 关闭套接字和清理 Winsock
closesocket(
1、打开你要写c++程序的文件夹,我们这里新建一个Test文件夹并打开test,打开后:使用VScode运行调试C/C++,在左侧打开的目录中新建一个 main.cpp 文件。
2、新建后点左侧的调试按钮(英文:Debug),可以看到,目前没有调试配置。
3、这时我们需要配置自己的调试配置,回到资源管理器界面,我们可以看到目录下多了一个.vscode的文件夹,里面有一个launch.json文件。我们现在在这个文件夹中新建一个tasks.json文件。我们需要改写这两个json文件的内容。
{
version: 0.2.0,
configurations: [
{
name: Run C/C++,
type: cppdbg,
request: launch,
program: ${workspaceFolder}/${fileBasenameNoExtension}.exe,
args: [],
stopAtEntry: false,
cwd: ${workspaceFolder},
environment: [],
externalConsole: true,
MIMode: gdb,
miDebuggerPath: C:/Program Files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/gdb.exe,
setupCommands: [
{
description: Enable pretty-printing for gdb,
text: -enable-pretty-printing,
ignoreFailures: false
}
],
preLaunchTask: build &run file
},
{
name: Debug C/C++,
type: cppdbg,
request: launch,
program: ${workspaceFolder}/${fileBasenameNoExtension}.exe,
args: [],
stopAtEntry: false,
cwd: ${workspaceFolder},
environment: [],
externalConsole: true,
MIMode: gdb,
miDebuggerPath: C:/Program Files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/gdb.exe,
setupCommands: [
{
description: Enable pretty-printing for gdb,
text: -enable-pretty-printing,
ignoreFailures: false
}
],
preLaunchTask: build &debug file
}
]
}
其中tasks.json文件内容(直接复制即可):
{
version: 2.0.0,
tasks: [
{
label: build &debug file,
type: shell,
command: g++,
args: [
-g,
-o,
${fileBasenameNoExtension},
${file}
],
group: {
kind: build,
isDefault: true
}
},
{
label: build &run file,
type: shell,
command: g++,
args: [
-o,
${fileBasenameNoExtension},
${file}
],
group: {
kind: build,
isDefault: true
}
}
]
}
4、我们已经完成了基本的配置工作,保存以上两个json文件后,再次点击左侧的调试按钮(Debug),可以发现出现了两个新的配置,一个是直接运行程序的Run,一个是用来调试程序的Debug。
5、我们写一个简单的c++程序来进行调试说明,程序源代码,我们在return 0这行添加了一个断点。
6、切换运行配置为Debug C/C++,点击运行按钮开始调试。
7、可以看到,d出的终端输出了正确的结果,调试窗口中的变量中也有变量a和对应的值。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)