weixin_36505189
weixin_36505189
采纳率75%
2017-06-01 11:05

C++服务端发送给客户端消息,但客户端没有显示

2
已采纳

服务端代码:
#include"iostream"
#include
#pragma comment(lib,"ws2_32")
#include
using namespace std;
int main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in sockaddr;
sockaddr.sin_family = PF_INET;
sockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
sockaddr.sin_port = htons(827);
bind(s, (SOCKADDR*)&sockaddr, sizeof(SOCKADDR));

listen(s, 1);

SOCKADDR clientAddr;
int nSize = sizeof(SOCKADDR);
SOCKET clientSock;
clientSock = accept(s, (SOCKADDR*)&clientAddr, &nSize);

send(clientSock,
    "helllo client \r\n",
    strlen("hello client \r\n") + sizeof(char),
    NULL);

closesocket(clientSock);
closesocket(s);

WSACleanup();
return 0;

}

客户端代码:
#include"iostream"
#include
#include
#pragma comment(lib,"ws2_32")
using namespace std;
int main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);

SOCKET s = socket(PF_INET,SOCK_STREAM, IPPROTO_TCP);

sockaddr_in sockAddr;
sockAddr.sin_family = PF_INET;
sockAddr.sin_addr.S_un.S_addr = inet_addr("127,0,0,1");
sockAddr.sin_port = htons(827);

connect(s, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));

char szBuffer[MAXBYTE] = { 0 };

recv(s, szBuffer, MAXBYTE, NULL);

printf("szBuffer=%s\r\n", szBuffer);

closesocket(s);
WSACleanup();
return 0;

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • caozhy 回答这么多问题就耍赖把我的积分一笔勾销了 4年前

    抓包工具看下,是不是防火墙阻拦了,ip地址是否正确,网络是否通?如果是内网,有没有端口映射?

    点赞 1 评论 复制链接分享
  • shen_wei shen_wei 4年前

为你推荐