2017年本科毕业,经历过千辛万苦的找工作之后,我进入了现在的这家公司。虽是职场小白,但励志成为IT界的一股清流(毕竟开发的妹子少,哈哈)。因为公司的业务需要,我负责的部分是利用组播技术实现OSG模型的多人协同操作,简单来说就是,在n个多播组中,无论任何一个成员操作模型,其所在组内的其他成员的模型也会随之改变。
udp技术就不多说了,度娘都有,我的理解就是一对多的通信模式。我采用的是C/S架构,客户端和服务器不再是傻瓜式的收-发-收-发模式,而是像我们日常用QQ群、微信群一样,一方可以毫无顾忌的发送消息(传说中的索命连环call),也可以接受到其他成员的,部分核心代码如下:
客户端加入到多播组:
1 #define PORT 9999 2 #define BUF_SIZE 1024 3 4 int main() 5 { 6 WSADATA wsaData; 7 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) 8 { 9 cout << "Failed to load Winsock dll" << WSAGetLastError(); 10 } 11 12 SOCKET clientSock = socket(AF_INET, SOCK_DGRAM, 0);//创建套接字 13 if (clientSock == INVALID_SOCKET) 14 { 15 cout << "socket()Failed:" << WSAGetLastError(); 16 } 17 18 sockaddr_in servAddr;//地址信息 19 memset(&servAddr, 0, sizeof(servAddr)); 20 servAddr.sin_addr.s_addr = inet_addr("192.168.0.121"); 21 servAddr.sin_family = AF_INET; servAddr.sin_port = htons(PORT); 22 int len = sizeof(servAddr); 23 char sendBuf[BUF_SIZE] = { 0 };//缓冲区初始化为0 24 25 if (sendto(clientSock, sendBuf, BUF_SIZE, 0, (sockaddr*)&servAddr, len) == SOCKET_ERROR) 26 { 27 cout << "send failed ,error is:" << WSAGetLastError() << endl; 28 } 29 else 30 { 31 cout << "send successfully:" << sendBuf << endl; 32 } 33 34 //加入到多播组 35 bool loop = 1; 36 if (setsockopt(clientSock, IPPROTO_IP, IP_MULTICAST_LOOP, reinterpret_cast<char FAR *>(&loop), sizeof(loop)) < 0) 37 { 38 cout << "set sock error" << endl; 39 return false; 40 } 41 struct ip_mreq mreq; 42 mreq.imr_multiaddr.S_un.S_addr = inet_addr(groupIP.c_str()); 43 mreq.imr_interface.s_addr = inet_addr(myIP.c_str()); 44 setsockopt(clientSock, IPPROTO_IP, IP_ADD_MEMBERSHIP, reinterpret_cast<char FAR *>(&mreq), sizeof(mreq)); 45 }
自定义发送和接收函数:(敲黑板:接收函数有亮点,发现没,设置接收时间的巧妙之处在哪呢?请见下回分解,哈哈)
1 //服务器也可以发送消息,调用下SendMessage函数即可 2 3 void SendMessage(string str, sockaddr_in addr) 4 { 5 char * send_buff = new char[str.length() + 1]; 6 strcpy(send_buff, str.c_str()); 7 8 if (sendto(SerSocket, send_buff, str.length() + 1, 0, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) 9 { 10 cout << "failed to send the msg , with the error is : " << WSAGetLastError() << endl; 11 return; 12 } 13 }
1 //客户端不光是发送请求的一方,也是接收消息的一方 2 3 bool recvMsg(string &str, int ms) //规定时间内接收 4 { 5 char recvBuf[BUF_SIZE] = { 0 }; //初始化缓冲区 6 7 int len = sizeof(servAddr); 8 int timer = 0; int SocketError; 9 while (timer <= ms) 10 { 11 if(recvfrom(clientSock, recvBuf, BUF_SIZE, 0, (sockaddr*)&servAddr, &len) == SOCKET_ERROR) 12 { 13 SocketError = WSAGetLastError(); 14 if (SocketError != WSAEWOULDBLOCK) 15 { 16 cout << endl << "socket error is:" << SocketError << endl << endl; 17 } 18 ++timer; 19 } 20 else 21 { 22 str = recvBuf; 23 cout << "receive from server:" << str.c_str() << endl; 24 return true; 25 } 26 Sleep(1); 27 } 28 if (timer > ms) 29 { 30 return false; 31 } 32 }
网络编程,socket的头文件不要忘了哦
1 #include<WinSock2.h> 2 #include<ws2tcpip.h> 3 #include<iostream> 4 #pragma comment ( lib,"ws2_32.lib" ) 5 using namespace std;
第一次写博客,排版什么的还不太懂,如果文中有什么不正确的地方,还望各位大佬指教,谢谢啦~