我想知道为什么在使用带有套接字的线程时我无法发送数据。
我想知道为什么当我使用第一种方法(无线程)发送时,它可以工作,但使用第二种方法,它无法发送数据。
这是我的声明:
int main(int argc, char *argv[])
{
int sd, rc, i;
struct sockaddr_in cliAddr, remoteServAddr;
struct hostent *h;
h = gethostbyname(argv[1]);
inet_ntoa(*(struct in_addr *)h->h_addr_list[0]));
remoteServAddr.sin_family = h->h_addrtype;
memcpy((char *) &remoteServAddr.sin_addr.s_addr,h->h_addr_list[0], h->h_length);
remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT);
/* socket creation */
sd = socket(AF_INET,SOCK_DGRAM,0);
/* bind any port */
cliAddr.sin_family = AF_INET;
cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
cliAddr.sin_port = htons(0);
rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));
socklen_t remoteServLen = sizeof(remoteServAddr);
//this is my own class to store the pointers to the following variables
clientInfo ci(&sd,&rc,&remoteServLen,&remoteServAddr,&cliAddr);
/第一种方法/
char *data;
char input[MAX_MSG];
std::cout << "Enter message to send (type /q to quit) : ";
std::cin >> input;
data = input;
rc = sendto(*(ci.getSd()), data, strlen(data)+1, 0,(struct sockaddr *) ci.getCliAddr(),*(ci.getCliLen()));
/第一种方法/
/第二种方法/
pthread_t thread[2];
int status;
status = pthread_create (&thread[1], NULL, sendFunction,&ci);
/第二种方法/
}
/这是我的线程方法/
void* sendFunction (void* temp)
{
int status;
char *data;
char input[MAX_MSG];
int rc;
clientInfo *ci;
ci = (clientInfo*)temp;
status = pthread_detach (pthread_self ());
while(1)
{
std::cout << "Enter message to send (type /q to quit) : ";
std::cin >> input;
data = input;
rc = sendto(*(ci->getSd()), data, strlen(data)+1, 0,(struct sockaddr *) ci->getCliAddr(),*(ci->getCliLen()));
if(rc<0)
{
printf("Cannot send data %s \n",data);
}
}//end of while loop
return NULL;
}//end of sendFunction method
:) 提前致谢!:D