라즈베리 파이에 서버가 있고 멀티 스레딩을 허용하고 싶습니다. 서버가 작동 중입니다. 클라이언트가 창에 있습니다. pthread_create를 통해 소켓 ID를 보내야한다고 생각하지만 방법을 찾지 못했습니다. 보내야 할 다른 것이 있습니까? 이를 수행하는 가장 좋은 방법은 무엇입니까?
인터넷을 검색하고 stackoverflow가 포함되어 있으며 몇 가지 해결 방법을 시도했지만 작동하지 않았습니다.
const int PORT = 12000;
TCPServer tcp;
pthread_t my_thread[MAXCLIENTQUEUE];
int clientID = 0;
int main()
{
tcp.setup(PORT);
int clientQueueSize = 0, threadJoin = 0;
void *res;
do {
socklen_t sosize = sizeof(tcp.clientAddress);
//realizar o accept
tcp.newsockfd[clientQueueSize] = accept(tcp.sockfd, (struct sockaddr*) & tcp.clientAddress, &sosize);
if (tcp.newsockfd[clientQueueSize] == -1)
{
cout << "Error accepting -> " << tcp.newsockfd[clientQueueSize] << endl;
tcp.detach();
}
cout << ">- accept: " << strerror(errno) << " / codigo: " << tcp.newsockfd[clientQueueSize] << " - Endereco: " << inet_ntoa(tcp.clientAddress.sin_addr) << endl;
clientID++;
cout << ">>> client accepted" << " | Client ID: " << clientID << endl;
// criar threads
int ret = pthread_create(&my_thread[clientQueueSize], NULL, messenger, &tcp.newsockfd[clientQueueSize]);
cout << ">- pthread: " << strerror(errno) << " / codigo: " << ret << endl;
if (ret != 0) {
cout << "Error: pthread_create() failed\n" << "thread_n " << my_thread[clientQueueSize] << endl;
exit(EXIT_FAILURE);
}
cout << "thread n " << my_thread[clientQueueSize] << endl;
clientQueueSize++;
}
while (clientQueueSize < MAXCLIENTQUEUE);
pthread_exit(NULL);
return 0;
}
서버는 다중 연결을 허용하지만 첫 번째 클라이언트에만 메시지를 보내고 다른 클라이언트는 성공적으로 연결되지만 메시지를 수신하지 않습니다. 서버가 모든 클라이언트에게 메시지를 보낼 수 있기를 바랍니다.
모든 소켓에 대한 스레드를 만들어야합니다. 또는 Windows 종속 비동기 선택 방법을 사용합니다.
PS pthread를 잊어 버리고 표준 std :: thread 사용하십시오 .
map<SOCKET,std::string> clients;
void newclient(SOCKET x)
{
for(;;)
{
int r = recv(x,...);
if (r == 0 || r == -1)
break;
}
// remove it from clients, ensure proper synchronization
}
void server()
{
SOCKET x = socket(...);
bind(x,...);
listen(x,...);
for(;;)
{
auto s = accept(x,...);
if (s == INVALID_SOCKET)
break;
// save to a map, for example, after ensuring sync with a mutex and a lock guard
m[s] = "some_id";
std::thread t(newclient,s);
s.detach();
}
}
int main() //
{
// WSAStartup and other init
std::thread t(server);
t.detach();
// Message Loop or other GUI
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다