详谈C++ socket网络编程实例

2021-11-19 12:52:56 来源:易采站长站 作者:

详谈C++ socket网络编程实例,客户端,数据,协议,族类,功能

详谈C++ socket网络编程实例

易采站长站,站长之家为您整理了详谈C++ socket网络编程实例的相关内容。

目录
功能源码效果总结

功能

实现基于sokcet的Cpp服务端

TIPS:功能包括接收客户端的数据,向客户端发送数据。

源码

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <iostream>
//#include <windows.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32")
using std::cout;
using std::endl;
using std::cin;

int main()
{
	system("chcp 65001");
	//SetConsoleOutputCP(65001);
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);//启动window动态网络库
	//1.创建socket
	//SOCKET == 句柄 == 文件描述符 == 套接字
	//socket(协议族类型,协议类型,0);
	//协议族类型 IPV4(AF_INET) IPV6
	//协议类型 TCP(SOCK_STREAM),UDP(SOCK_DROP)
	SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);//IPPROTO_TCP
	if (serverSocket == INVALID_SOCKET)
	{
		cout << "创建socket失败" << endl;
		return 0;
	}
	//2.绑定ip和端口号
	//127.0.0.1 永远指向本机
	//0.0.0.o 绑定所有网卡的ip
	SOCKADDR_IN serverAddr;
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(7890);//host to networks short,将主机字节序转化为网络字节序
	serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");//点分十进制转换为10进制
	if (SOCKET_ERROR == bind(serverSocket, (sockaddr *)&serverAddr, sizeof(SOCKADDR_IN)))
	{
		cout << "bind 失败" << endl;
		return 0;
	}
	cout << "bind 成功" << endl;
	//3.监听,提示本机的操作系统
	if (INVALID_SOCKET == listen(serverSocket, 5))
	{
		cout << "listen 失败" << endl;
		return 0;
	}
	cout << "listen 成功" << endl;
	while(true)
	{
		//4.等待客户端连接
		SOCKADDR_IN clientAddr;
		int addrLen = sizeof(SOCKADDR_IN);
		SOCKET clientSocket = accept(serverSocket, (SOCKADDR *)&clientAddr, &addrLen);
		if (INVALID_SOCKET == clientSocket)
		{
			cout << "客户端连接失败 " << endl;
			return 0;
		}
		cout << "client ok " << inet_ntoa(clientAddr.sin_addr) << endl;
		cout << "port " << ntohs(clientAddr.sin_port) << endl;
		//5.收发数据
		//接收数据
		char recvBuffer[1024]{ 0 };
		int nRecv = recv(clientSocket, recvBuffer, 1024, 0);
		cout << "recvLen:" << nRecv << "内容:" << recvBuffer << endl;
		//发送数据
		int nSend = send(clientSocket, recvBuffer, nRecv, 0);
		cout << "send Len:" << nSend << endl;
		//6.关闭客户端
		closesocket(clientSocket);
	}
	//7.关闭服务端
	closesocket(serverSocket);

	WSACleanup();//卸载window动态网络库
	return 0;
}

效果

TIPS:利用sokit模拟工具模拟一个客户端终端。

效果图

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注易采站长站的更多内容!

以上就是关于对详谈C++ socket网络编程实例的详细介绍。欢迎大家对详谈C++ socket网络编程实例内容提出宝贵意见

微信扫一扫

易采站长站微信账号
'); })();