Socket实现通讯 两台设备之间传输信息 C++实现

本文介绍了使用C++在Visual Studio 2010下实现Socket通信的过程,包括服务器和客户端的项目设置,如添加ws2_32.lib库。在测试时,通过两台设备进行交互,展示了如何在命令行中输入IP地址和端口号进行连接。文章强调了TCP协议的ACK机制,并鼓励读者在遇到问题时进行互动讨论。
摘要由CSDN通过智能技术生成

实现的编译器是 Visual Studio 2010, 之前用的2022太新,一些头文件用不了

写的过程中对数据在传输层的通讯 ACK TCP 协议都有了新的理解

服务端和客户端分开两个project:运行注意事项:
// Server.cpp : create a console application, and include the sources in the project
//
// 1. open the *.c in the Visual C++, then “rebuild all”.
// 2. click “yes” to create a project workspace.
// 3. You need to -add the library ‘ws2_32.lib’ to your project
// (Project -> Properties -> Linker -> Input -> Additional Dependencies)
// 4. recompile the source.

代码
Server:
// You need to -add the library ‘ws2_32.lib’ to your project

#include “stdafx.h”
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define DEFAULT_PORT 5019//持续监听5019端口

int main(int argc, char **argv){

char szBuff[100];//The information of the message need to transimit
int msg_len;//the length of the message
int addr_len;//the length of the address
struct sockaddr_in local, client_addr;

SOCKET sock, msg_sock;
WSADATA wsaData;

//514
if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR){
	// stderr: standard error are printed to the screen.
	fprintf(stderr, "WSAStartup failed with error %d\n", WSAGetLastError());
	//WSACleanup function terminates use of the Windows Sockets DLL. 
	WSACleanup();
	return -1;
}
// Fill in the address structur
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
你可以使用Boost库中的Asio模块来实现两台电脑之间的连接与消息传输。下面是一个简单的示例代码,演示了如何在两台电脑之间建立TCP连接并传输消息。 首先,确保你已经安装了Boost库,并将其包含在你的代码中。 ```cpp #include <iostream> #include <boost/asio.hpp> using boost::asio::ip::tcp; int main() { try { // 创建一个io_context对象 boost::asio::io_context io_context; // 创建一个TCP socket tcp::socket socket(io_context); // 解析服务器的IP地址和端口号 tcp::resolver resolver(io_context); auto endpoints = resolver.resolve("服务器IP地址", "端口号"); // 连接到服务器 boost::asio::connect(socket, endpoints); // 发送消息 std::string message = "Hello, server!"; boost::asio::write(socket, boost::asio::buffer(message)); // 接收响应 char reply[1024]; size_t reply_length = boost::asio::read(socket, boost::asio::buffer(reply, message.size())); std::cout << "Reply from server: "; std::cout.write(reply, reply_length); std::cout << std::endl; } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; } ``` 在代码中,你需要将"服务器IP地址"替换为实际的服务器IP地址,"端口号"替换为实际的端口号。首先,创建一个io_context对象来处理底层网络操作。然后,创建一个TCP socket,并通过resolver解析服务器的地址和端口。接下来,使用socket连接到服务器。发送消息时,使用boost::asio::write函数发送数据,接收响应时,使用boost::asio::read函数接收数据。 请记住,这只是一个基本的示例,你可能需要根据你的具体需求进行修改和扩展。此外,你还需要在服务器实现相应的逻辑来处理接收到的消息。 希望这可以帮助到你!如有任何问题,请随时提问。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值