連接建立了,語言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!\n");
if (sClient==INVALID_SOCKET)
{
printf("accept failed!\n");
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!\n");
if (errcode==SOCKET_ERROR)
{
printf("recv failed!\n");
closesocket(sClient);
break;
}
else
{
printf("%d\n%s\n",gk.a,gk.b);
printf("want to send %s\n",ans);
errcode=send(sClient,ans,128,0);printf("send ing!\n");
if (errcode==SOCKET_ERROR)
{
printf("send failed!\n");
closesocket(sClient);
break;
}
}
closesocket(sClient);
}
closesocket(sServer);printf("close!\n");
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!\n");
errcode=send(sClient,ans,strlen(ans),0);printf("send ing!\n");