问题描述
- 客户端发送消息给服务端后,服务端应答无效
-
连接建立了,语言C++。前端是用cocos2d封装好的。
目前是:客户端向服务端send:服务端能接到;服务端向客户端send:客户端能接到。
但是:客户端向服务端send,服务端接到后立即应答向客户端send,客户端就接不到。
代码如下:
客户端:(在一个按钮中触发)gksock->connect_(5500,"127.0.0.1"); struct gksakura { int a; char b[32]; }; struct gksakura gk; ZeroMemory(&gk,sizeof(gk)); gk.a=32; strcpy(gk.b,"matousakura"); char ans[64]; ZeroMemory(ans,sizeof(ans)); auto errcode =gksock->send((char*)&gk,128); if (errcode!=SOCKET_ERROR) { CCLOG("!!!!!!!!!!!!!!!!!!!!!!!!!"); gksock->recv(ans,128); CCLOG("%s",ans); } gksock->close();
服务端:
while(1) { SOCKET sClient=accept(sServer,(SOCKADDR*)&addrclient,&addrclientlen);printf("accetp ing! "); if (sClient==INVALID_SOCKET) { printf("accept failed! "); break; } struct gksakura { int a; char b[32]; }; struct gksakura gk; ZeroMemory((char*)&gk,sizeof((char*)&gk)); char ans[]="get it!"; errcode=recv(sClient,(char*)&gk,128,0);printf("recv ing! "); if (errcode==SOCKET_ERROR) { printf("recv failed! "); closesocket(sClient); break; } else { printf("%d %s ",gk.a,gk.b); printf("want to send %s ",ans); errcode=send(sClient,ans,128,0);printf("send ing! "); if (errcode==SOCKET_ERROR) { printf("send failed! "); closesocket(sClient); break; } } closesocket(sClient); } closesocket(sServer);printf("close! "); WSACleanup();
解决方案
楼主,你代码内存越界了
1.客户端发送的时候,读越界,接收的时候,写越界;
2.服务器接收的时候,写越界,发送的时候,读越界。
建议代码修改如下:
1.客户端
auto errcode =gksock->send((char*)&gk,sizeof(gk));
gksock->recv(ans,sizeof(ans));
2.服务器
errcode=recv(sClient,(char*)&gk,sizeof(gk),0);printf("recv ing!
");
errcode=send(sClient,ans,strlen(ans),0);printf("send ing!
");
解决方案二:
黑马程序员-网络编程客户端向服务端发送文件
时间: 2024-09-30 08:35:53