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;
return0;
}
//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;
return0;
}
cout <<"bind 成功"<< endl;
//3.监听,提⽰本机的操作系统
if(INVALID_SOCKET ==listen(serverSocket,5))
{
cout <<"listen 失败"<< endl;
return0;
}
cout <<"listen 成功"<< endl;
while(true)
{
//4.等待客户端连接
//4.等待客户端连接
SOCKADDR_IN clientAddr;
int addrLen =sizeof(SOCKADDR_IN);
SOCKET clientSocket =accept(serverSocket,(SOCKADDR *)&clientAddr,&addrLen); if(INVALID_SOCKET == clientSocket)
{
cout <<"客户端连接失败 "<< endl;
return0;
}
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动态⽹络库
socket编程聊天室基本流程
return0;
}
效果
TIPS:利⽤sokit模拟⼯具模拟⼀个客户端终端。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论