簡體   English   中英

為什么accept()(用於套接字連接)導致我的代碼被阻止?

[英]Why does the accept() (for socket connections) cause my code to block?

當我運行代碼時,似乎這一行沒有運行整個main函數

connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len); 

在里面。 它甚至不會在開始時就打印第一個提示,但是當我注釋掉它時,它可以正常工作,有人可以告訴我原因嗎?

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <iostream>

#define PORT 1227
#define SIM_LENGTH 10;
using namespace std;
void clean_up(int cond, int *sock){
cout<<"exiting";
close(*sock);
exit(cond);
}

int main(void){
cout<<"working;
int sock;
int connect_sock;
struct sockaddr_in serv_name;
size_t len;
int count;

sock =  socket(AF_INET, SOCK_STREAM, 0);
if(sock<0){
cout<<"Error connecting to socket";
clean_up(1, &sock);
}
bzero(&serv_name, sizeof(serv_name)); // set name as physical address
serv_name.sin_family = AF_INET;
serv_name.sin_port = htons(PORT);
if(bind(sock,(struct sockaddr *)&serv_name, sizeof(serv_name))<0){
cout<<"error naming channel";
clean_up(1, &sock);
}
cout<<"waiting for connection from client";
listen(sock, 1);
len = sizeof(serv_name);
connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len);
cout<<connect_sock;
cout<<"server wrote";
close(connect_sock);
cout<<"connect?";
}

它正在等待連接。 它不打印第一cout因為你沒有要求它。 嘗試:

cout<<"waiting for connection from client"<<endl;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM