详谈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网络编程实例

基础教程推荐