ANTICHAT.XYZ    VIDEO.ANTICHAT.XYZ    НОВЫЕ СООБЩЕНИЯ    ФОРУМ  
Баннер 1   Баннер 2
Antichat снова доступен.
Форум Antichat (Античат) возвращается и снова открыт для пользователей. Здесь обсуждаются безопасность, программирование, технологии и многое другое. Сообщество снова собирается вместе.
Новый адрес: forum.antichat.xyz
Вернуться   Форум АНТИЧАТ > Программирование > PHP, PERL, MySQL, JavaScript
   
Ответ
 
Опции темы Поиск в этой теме Опции просмотра

Эмуляция многопоточности в php
  #1  
Старый 09.06.2009, 20:43
Аватар для Ru}{eeZ
Ru}{eeZ
Постоянный
Регистрация: 19.02.2008
Сообщений: 438
Провел на форуме:
956872

Репутация: 186
Отправить сообщение для Ru}{eeZ с помощью ICQ
По умолчанию Эмуляция многопоточности в php

Помогите разобраться с многопоточностью в php. Написал сервер, но как вы уже догадались, он работает только с одним человеком. Я с этим уже заебался...
PHP код:
<?php
$addr 
'127.0.0.1';
$port 4941;
$password 987654321;
$icq 595778;
$email 'm-comp@mail.ru';
set_time_limit(0);
if(!
$socket socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) socket_strerror(socket_last_error()) && die;
@
socket_bind($socket,$addr,$port) or die;
socket_listen($socket,10) or socket_strerror(socket_last_error()) && die;
for(;;) {
  if(!
$accept socket_accept($socket)) socket_strerror(socket_last_error()) && die;
  
socket_write($accept,'Welcome to the RuXeeZ server! Please enter "!help" for view more information.'."\r\n\r\n") or socket_strerror(socket_last_error()) && die;
  for(;;) {
    if(!
$read socket_read($accept,256,PHP_NORMAL_READ)) break;
    
$read trim($read);
    if(
$read == '!close') break;
    else if(
strstr($read,'!stop') && ltrim(substr($read,5)) == $password) {
      
socket_close($accept);
      break 
2;
    }
    else if(
$read == '!help') {
    
$say '   --System functions--
!close - close this connection
!help - view more information
!contacts - contact to administration'
."\r\n".'
   --Other functions---
!base64e text - encode text in base64 hash
!base64d text - decode base64 hash in text
!md5 text - encode text in md5 hash
!sha1 text - encode text in sha1 hash
!rot13 text - encode text in rot13 hash'
."\r\n";
    } else if(
$read == '!contacts'$say 'ICQ: '.$icq."\r\n".'E-mail: '.$email;
    else if(
strstr($read,'!base64e')) $say base64_encode(ltrim(substr($read,8)));
    else if(
strstr($read,'!base64d')) $say base64_decode(ltrim(substr($read,8)));
    else if(
strstr($read,'!md5')) $say md5(ltrim(substr($read,4)));
    else if(
strstr($read,'!sha1')) $say sha1(ltrim(substr($read,5)));
    else if(
strstr($read,'!rot13')) $say str_rot13(ltrim(substr($read,6)));
    else 
$say 'Not correct command';
    
socket_write($accept,$say."\r\n\r\n") or socket_strerror(socket_last_error()) && die;
  }
  
socket_close($accept);
}
socket_close($socket);
//echo 'Server is stoped';
?>
прошу непонимающих не лезть со ссылками

Последний раз редактировалось Ru}{eeZ; 09.06.2009 в 20:45..
 
Ответить с цитированием

  #2  
Старый 09.06.2009, 20:49
Аватар для Ctacok
Ctacok
Moderator - Level 7
Регистрация: 19.12.2008
Сообщений: 1,203
Провел на форуме:
5011696

Репутация: 2221


По умолчанию

Цитата:
socket_write($accept,'Welcome to the RuXeeZ server! Please enter "!help" for view more information.'."\r\n\r\n") or socket_strerror(socket_last_error()) && die;
"!help" под '', у меня вызывает краш.
"Всё самое сложное, самое простое" - (c) HZ.
Проверь корректность всего кода.
 
Ответить с цитированием

  #3  
Старый 09.06.2009, 20:52
Аватар для Ru}{eeZ
Ru}{eeZ
Постоянный
Регистрация: 19.02.2008
Сообщений: 438
Провел на форуме:
956872

Репутация: 186
Отправить сообщение для Ru}{eeZ с помощью ICQ
По умолчанию

Цитата:
Сообщение от Ctacok  
"!help" под '', у меня вызывает краш.
"Всё самое сложное, самое простое" - (c) HZ.
Проверь корректность всего кода.
я не просил проверять код, сервер написан под одного клиента, а нужно, чтобы его могли использовать несколько человек сразу.
Зачем лезть (в данном случае флудить), если не разбираешься? (вопрос, не нуждающийся в ответе)
 
Ответить с цитированием

  #4  
Старый 09.06.2009, 21:03
Аватар для FireFenix
FireFenix
Постоянный
Регистрация: 03.06.2009
Сообщений: 385
Провел на форуме:
3178262

Репутация: 389
По умолчанию

Цитата:
Сообщение от Ru}{eeZ  
я не просил проверять код, сервер написан под одного клиента, а нужно, чтобы его могли использовать несколько человек сразу.
Зачем лезть (в данном случае флудить), если не разбираешься? (вопрос, не нуждающийся в ответе)
http://php.net/manual/en/ref.pcntl.php
http://habrahabr.ru/blogs/php/40245/ - пример с сокетами
 
Ответить с цитированием

  #5  
Старый 09.06.2009, 21:19
Аватар для diehard
diehard
Постоянный
Регистрация: 30.09.2007
Сообщений: 815
Провел на форуме:
2590715

Репутация: 659


Отправить сообщение для diehard с помощью ICQ
По умолчанию

блин подобная тема поднимается на форуме каждые несколько месяцев, ТС пользуйся поиском
 
Ответить с цитированием

  #6  
Старый 09.06.2009, 22:48
Аватар для Gifts
Gifts
Reservists Of Antichat - Level 6
Регистрация: 25.04.2008
Сообщений: 827
Провел на форуме:
2769640

Репутация: 1304


По умолчанию

Ru}{eeZ http://ru2.php.net/manual/ru/sockets.examples.php - пример из мануала, нумер 1, ретранслирует текст, принимает команды.

З.Ы нафига маны читать?
 
Ответить с цитированием

  #7  
Старый 10.06.2009, 13:21
Аватар для Ru}{eeZ
Ru}{eeZ
Постоянный
Регистрация: 19.02.2008
Сообщений: 438
Провел на форуме:
956872

Репутация: 186
Отправить сообщение для Ru}{eeZ с помощью ICQ
По умолчанию

Цитата:
Сообщение от Gifts  
Ru}{eeZ http://ru2.php.net/manual/ru/sockets.examples.php - пример из мануала, нумер 1, ретранслирует текст, принимает команды.

З.Ы нафига маны читать?
так там такое же сервер, как и у меня, он всех клиентов в очередь ставит
 
Ответить с цитированием

  #8  
Старый 10.06.2009, 14:19
Аватар для Gifts
Gifts
Reservists Of Antichat - Level 6
Регистрация: 25.04.2008
Сообщений: 827
Провел на форуме:
2769640

Репутация: 1304


По умолчанию

Ru}{eeZ Хм, ну да, я вас обманул, помню что брал пример с php.net в свое время, но из другого топика. Вот скрипт (из комментов к функции socket_select)

PHP код:
#!/usr/local/bin/php
<?php

    $port 
9050;
   
    
// create a streaming socket, of type TCP/IP
    
$sock socket_create(AF_INETSOCK_STREAMSOL_TCP);
   
    
// set the option to reuse the port
    
socket_set_option($sockSOL_SOCKETSO_REUSEADDR1);
   
    
// "bind" the socket to the address to "localhost", on port $port
    // so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc..
    
socket_bind($sock0$port);
   
    
// start listen for connections
    
socket_listen($sock);

    
// create a list of all the clients that will be connected to us..
    // add the listening socket to this list
    
$clients = array($sock);
   
    while (
true) {
        
// create a copy, so $clients doesn't get modified by socket_select()
        
$read $clients;
       
        
// get a list of all the clients that have data to be read from
        // if there are no clients with data, go to next iteration
        
if (socket_select($read$write NULL$except NULL0) < 1)
            continue;
       
        
// check if there is a client trying to connect
        
if (in_array($sock$read)) {
            
// accept the client, and add him to the $clients array
            
$clients[] = $newsock socket_accept($sock);
           
            
// send the client a welcome message
            
socket_write($newsock"no noobs, but ill make an exception :)\n".
            
"There are ".(count($clients) - 1)." client(s) connected to the server\n");
           
            
socket_getpeername($newsock$ip);
            echo 
"New client connected: {$ip}\n";
           
            
// remove the listening socket from the clients-with-data array
            
$key array_search($sock$read);
            unset(
$read[$key]);
        }
       
        
// loop through all the clients that have data to read from
        
foreach ($read as $read_sock) {
            
// read until newline or 1024 bytes
            // socket_read while show errors when the client is disconnected, so silence the error messages
            
$data = @socket_read($read_sock1024PHP_NORMAL_READ);
           
            
// check if the client is disconnected
            
if ($data === false) {
                
// remove client for $clients array
                
$key array_search($read_sock$clients);
                unset(
$clients[$key]);
                echo 
"client disconnected.\n";
                
// continue to the next client to read from, if any
                
continue;
            }
           
            
// trim off the trailing/beginning white spaces
            
$data trim($data);
           
            
// check if there is any data after trimming off the spaces
            
if (!empty($data)) {
           
                
// send this to all the clients in the $clients array (except the first one, which is a listening socket)
                
foreach ($clients as $send_sock) {
               
                    
// if its the listening sock or the client that we got the message from, go to the next one in the list
                    
if ($send_sock == $sock || $send_sock == $read_sock)
                        continue;
                   
                    
// write the message to the client -- add a newline character to the end of the message
                    
socket_write($send_sock$data."\n");
                   
                } 
// end of broadcast foreach
               
            
}
           
        } 
// end of reading foreach
    
}

    
// close the listening socket
    
socket_close($sock);
?>
 
Ответить с цитированием

  #9  
Старый 10.06.2009, 06:07
Аватар для nerezus
nerezus
Pagan Heart
Регистрация: 12.08.2004
Сообщений: 3,791
Провел на форуме:
6490435

Репутация: 2290


Отправить сообщение для nerezus с помощью ICQ
По умолчанию

НАхрена это делать на пхп? о_О
 
Ответить с цитированием

  #10  
Старый 10.06.2009, 10:01
Аватар для scrat
scrat
Постоянный
Регистрация: 08.04.2007
Сообщений: 853
Провел на форуме:
5812656

Репутация: 1540


Отправить сообщение для scrat с помощью ICQ
По умолчанию

php не тот язык для реализации конкретной задачи.
 
Ответить с цитированием
Ответ



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Books PHP FRAGNATIC PHP, PERL, MySQL, JavaScript 186 21.02.2010 02:41
Books PSalm69 Избранное 248 27.10.2009 04:52
На PHP, как на "Новые ворота"... Mertvii-Listopad Чужие Статьи 7 18.09.2006 12:42
Безопасность в Php, Часть Iii k00p3r Чужие Статьи 0 11.07.2005 19:02
Защищаем Php. Шаг за шагом. k00p3r Чужие Статьи 0 13.06.2005 11:31



Здесь присутствуют: 1 (пользователей: 0 , гостей: 1)
 


Быстрый переход




ANTICHAT.XYZ