为什么多线程时套接字不工作?

时间:2013-07-04 07:49:25

标签: c++ multithreading sockets winsock

我有一个非常简单的recvfrom()命令可以正常工作 - 只要它不在“另一个”线程中调用。

我会发布更多代码,但有相当多的代码,所以希望我可以过滤掉相关的位: 首先,我们有全局变量:SOCKET Socket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);

只要不涉及线程,这样就可以了:

char message[_max_message_];
struct sockaddr_in* from;
int r;
    int SenderAddrSize = sizeof (struct sockaddr);
    r=recvfrom(Socket,message,_max_message_,0,(struct sockaddr *)&from,&SenderAddrSize);
    printf("Bytes recieved: %i\nError Code: %i\n",r,WSAGetLastError);

现在我在一个线程后面有相同的代码,如下所示: pthread_create(&listener, NULL, listenloop, &Socket);

(代码基本上忽略了&socket。)

要从被调用线程执行的第一个recvfrom()返回-1,但来自“原始”线程(设置了网络)的recvfrom()成功填充message来自服务器的消息。

很好地告诉我我做错了什么?

编辑:我讨厌向陌生人扔十几行来帮助我,但我不认为如果不这样做,我会得到答案。所以,这是套件和kaboodle,略有编辑:

#include <iostream>
//#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>

#include <pthread.h>
#include <conio.h>

using namespace std;
#include <string>
//One thread shall listen continually for responses from the server.
/*The other thread shall listen continually for user input, and fire off user input at the local
 client to the server...*/

//#ifdef _WINDOWS
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>

SOCKET Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
inline int randport()
{
  return (50000 % rand() + 1000);
}
#define _serverip_ "***.***.***.***"
#define _welcome_ "Welcome,Wagon!"

#define _randomport_ 64000%rand()+100
#define _max_message_ 100

void *listenloop(void *arg)
{
  //SOCKET* listener = (SOCKET)arg;
  WSADATA WsaDat;
  WSAStartup(MAKEWORD(2, 0), &WsaDat);

  char message[_max_message_];
  //SOCKET listener=(SOCKET)arg;
  int r;
  //sockaddr_in SenderAddr;
  struct sockaddr_in from;
  //while (1){

  int SenderAddrSize = sizeof(struct sockaddr);
  r = recvfrom(Socket, message, _max_message_, 0, (struct sockaddr *) &from,
      &SenderAddrSize);
  printf("Thread Bytes recieved: %i\nThread Error Code: %i\n", r,
      WSAGetLastError);
  return NULL ;

  //}
  return NULL ;
}

int main()
{
  string user, pass, login;
  WSADATA WsaDat;
  WSAStartup(MAKEWORD(2, 0), &WsaDat);
  int port;
  cout << "Welcome!"
  SOCKET Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

  fflush(stdin); //As long as we compile with GCC Behavoir should be consistant

  //TRY NOT TO SEND PLAINTEXT PASSWORDS LIKE THIS!  IT MAY MAKE YOUR USERS VULNERABLE!  DONE FOR SAKE OF SIMPLICITY HERE!

  cout << "\n\nPlease enter the username you registered with:";
  getline(cin, user);
  cout << "\nPlease enter your password, my good sir: ";
  getline(cin, pass);
  struct hostent *host;
  host = gethostbyaddr(_serverip_, strlen(_serverip_), AF_INET);

  if (host == NULL )
  {
    cout << "\n\n UNABLE TO CONNECT TO SERVER.  QUITTING. ";
    return -1;
  }

  short errorcount = 3;
  int socketfeedback;

  ///Put the address for the server on the "evelope"

  SOCKADDR_IN SockAddr;
  SockAddr.sin_port = htons(port);
  SockAddr.sin_family = AF_INET;
  SockAddr.sin_addr.s_addr = inet_addr(_serverip_);

  ///Sign the letter...

  int myport = _randomport_;
  int code;

  SOCKADDR_IN service;
  service.sin_family = AF_INET;
  service.sin_addr.s_addr = inet_addr("localhost");
  service.sin_port = htons(myport);

  //bind(Socket, (SOCKADDR *) &service, sizeof(service));

  //Start a thread, listening for that server

  while ((errorcount))
  {
    code = bind(Socket, (SOCKADDR *) &service, sizeof(service));
    if (code)
      break;
    else
      return -5;
    errorcount--;
    myport = _randomport_;
    service.sin_port = htons(myport);
  }

  login = user + ',' + pass;

  if (!errorcount)
  {
    cout << "\n\nMiserable failure.  Last Known Error Code: " << code;
    return -1;
  }

  ///Begin the listen loop!!

  pthread_t listener;
  pthread_create(&listener, NULL, listenloop, &Socket);
  struct sockaddr result;
  sendto(Socket, login.c_str(), strlen(login.c_str()), 0,
      (struct sockaddr *) &SockAddr, sizeof(SockAddr));

  char message[_max_message_];
  //SOCKET listener=(SOCKET)arg;

  //sockaddr_in SenderAddr;
  struct sockaddr_in from;
  int r;
  int SenderAddrSize = sizeof(struct sockaddr);
  r = recvfrom(Socket, message, _max_message_, 0, (struct sockaddr *) &from,
      &SenderAddrSize);
  printf("Bytes recieved: %i\nError Code: %i\n", r, WSAGetLastError);

  //SOCKET listener=(SOCKET)arg;

  WSACleanup();

  return 0;

}

2 个答案:

答案 0 :(得分:1)

为什么使用全局Socket?为什么你在主要声明另一个Socket?您最好使用pthread_create中传递的套接字(只需将listenloop中的args转换为SOCKET *)。多线程中的全局变量是一个非常糟糕的想法(您需要同步机制)。并使用零来初始化struct sockaddr_in from(例如,使用memset,或者只需按照“我说struct sockaddr_in from = {0}”进行初始化。

而且您正在从两个不同线程中的一个套接字读取而没有任何同步。这必然会导致许多错误。

此外,我在其他帖子中看到了WSACleanuprecvfrom的问题。你不知道这两个运行的顺序是什么(所以你也可以在WSACleanup之前得到recvfrom。你可以使用pthread_join等待其他线程到完成后再做WSACleanup

答案 1 :(得分:0)

评论太长了。

由于声明:

,发布的代码根本不起作用
struct sockaddr_in* from;

然后像这样使用from

r=recvfrom(Socket,message,_max_message_,0,(struct sockaddr *)&from,&SenderAddrSize);

您正在设置struct sockaddr_in地址的地址,而不仅仅是其地址。

应该是:

r=recvfrom(Socket,message,_max_message_,0,(struct sockaddr *)from,&SenderAddrSize);

但是,如果这样做,则缺少将内存分配给from

如此可行

struct sockaddr_in* from;

是一个拼写错误,应阅读:

struct sockaddr_in from = {0};