C++的子线程里socket读写全都返回-1,怎么办。

qq_20570345 2018-10-29 07:39:57
这个程序的主线程和子线程一个负责写消息,一个负责读取消息,然而无论把写还是读放到子线程里,都会导致recv或者send返回-1,而放到主线程的那个都可以正常进行?


#include<iostream>
#include<strings.h>


#include "common.h"


using namespace std;

DWORD WINAPI ReadThread(LPVOID lpParameter);
SOCKET socktClient;
char name[20];


int main()
{
WORD wVersionRequested = MAKEWORD(2,2);
WSADATA wsaData;
if (WSAStartup(wVersionRequested,&wsaData))
{
cout<<"WSAStartup failed"<<endl;
}

SOCKET socktClient = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);

SOCKADDR_IN addrClient;
addrClient.sin_addr.S_un.S_addr = inet_addr(SERVER_IP);
addrClient.sin_family = AF_INET;
addrClient.sin_port = htons(SERVER_PORT);

//连接服务端
if (connect(socktClient,(SOCKADDR*)&addrClient,sizeof(SOCKADDR)))
{
cout<<"connect failed"<<endl;
}

Msg msg;
char buf[sizeof(msg)] = "";
//向服务端发送姓名
cout << "give me your name" << endl;
cin >> name;
memset(&buf,0, sizeof(buf));
buf[0] = '#';
int tot = 0;
while (name[tot] != '\0'){
buf[tot + 1] = name[tot++];
}
cout << buf << endl;
int nBytesSent = send(socktClient,buf,sizeof(buf),0);

//子线程建立
DWORD dwThreadIDRecv = 0;
DWORD dwThreadIDWrite = 0;
HANDLE hand = CreateThread(NULL,0, ReadThread,NULL,0,&dwThreadIDRecv);
if (hand == NULL) {
cout<<"Create work thread failed\n";
return -1;
}


//创建一个Msg,并发送给服务端
while (true) {
memset(&msg, 0, sizeof(msg));
memcpy(&msg.fromID, name, sizeof(name));
cout << "hisname" << endl;
cin >> buf;
memcpy(&msg.toID, buf, sizeof(msg.toID));
cout << "content" << endl;
cin >> buf;
memcpy(&msg.content, buf, sizeof(msg.content));
cout << msg.toID << ' ' << msg.content << endl;
memset(&buf, 0, sizeof(buf));
memcpy(&buf, &msg, sizeof(msg));

int nBytesSent = send(socktClient, buf, sizeof(buf), 0);
cout << "***Server#" << endl;
cout << buf << endl;

}
closesocket(socktClient);
return 0;
}


//比较函数
bool comp(char* a, char* b) {
int lena = strlen(a), lenb = strlen(b);
if (lena != lenb)
return false;
int i = 0, j = 0;
bool p = true;
while (a[i] != '\0' && i < lena && b[j] != '\0' && j < lenb) {
if (a[i++] != a[j++]) {
p = false;
break;
}
}
return p;
}

DWORD WINAPI ReadThread(LPVOID lpParameter) {
Msg msg;
char buf[sizeof(msg)] = "";
//接受一个msg,并判断是否符合要求
while (true) {
memset(&buf, 0, sizeof(buf));
int nBytesRecv = recv(socktClient,buf,sizeof(buf),0);
if (nBytesRecv <= 0)
continue;
memset(&msg, 0, sizeof(msg));
memcpy(&msg, buf, sizeof(msg));
if (comp(msg.fromID, name))
cout << "can't find this person" << endl;
else
cout << msg.fromID << ": " << msg.content << endl;
}
return 0;
}

服务端的写法和客户端是差不多的,但是服务端的子线程可以正常使用socket通讯
...全文
121 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

6,849

社区成员

发帖
与我相关
我的任务
社区描述
Windows 2016/2012/2008/2003/2000/NT
社区管理员
  • Windows Server社区
  • qishine
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧