qq_39588327
oldkeai
采纳率0%
2018-11-19 11:53

C++ socket 客户端recv不到数据

5

#include
#include /* for socket() and bind() /
#include /
for printf() and fprintf() /
#include /
for sockaddr_in and inet_ntoa() /
#include /
for close() /
#include /
for memset() /
#include /
for atoi() */

#include "Msg.h"
#include "queue"
#include "pack.h"
#include "analysis.h"
///////////////

using namespace std;
#define MYPORT 7000
#define SERVER_IP "127.0.0.1"

#define BUFFER_SIZE 1024
int sock_cli;//client文件描述符

void* recvMess(void* ptr) {
unsigned char recvbuf[BUFFER_SIZE];
while (1){
memset(recvbuf,0x00, sizeof(recvbuf));
cout<<"ready recv"<<endl;
int len = recv(sock_cli,recvbuf, sizeof(recvbuf),0);
if(len == -1){
cout << " client -1 recv error" << endl;
} else if (len == 0){
cout << "clent 0 recv over" << endl;
} else {
cout << len << endl;
}
}

int main()
{

///定义sockfd
//sock_cli = socket(AF_INET,SOCK_STREAM,0);
sock_cli = socket(AF_INET,SOCK_STREAM ,IPPROTO_TCP);
if(sock_cli <0){
    cout << "socket creatation failed!" << endl;
    return -1;
}
///定义sockaddr_in
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));

servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(MYPORT);  ///服务器端口
servaddr.sin_addr.s_addr = inet_addr(SERVER_IP);  ///服务器ip

if (connect(sock_cli, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
    perror("connect");
    exit(1);
}

pthread_t recv_szMessage_thread;
int  recv_szMessage_thread_flag = pthread_create(& recv_szMessage_thread,NULL,recvMess,NULL);
if ( recv_szMessage_thread_flag !=0){
    cout<< "client create recv thread failed"<<endl;
}
pthread_detach( recv_szMessage_thread);

while(1){
}
close(sock_cli);
return 0;

}

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

3条回答

  • phenix2009 白色一大坨 3年前

    这种代码网上多得是,你咋出的错呢,是不是服务器那边就没弄好,导致客户端没收到数据?

    点赞 评论 复制链接分享
  • qq_39588327 oldkeai 3年前

    当我把 服务端关闭时,就会recv的返回值是0

    点赞 评论 复制链接分享
  • devmiao devmiao 3年前

相关推荐