Question

Multi Thread PHP Port listener script.

Asked by: phenixfilms

Alrighty.....
To the person who can help i offer... 1 million dollars (contract subject to change as soon as you answer the question hehee)

so heres the idea... i need a script that sits on the server listening away for ever.  I connect via a socket to the server (using flash) Flash sends a command to the php listening script.  The script does some parsing magic etc and then echos results back to the swfs listening.  At the moment I have a script that listens and responds as mentioned above.... the problem however is if I have to swfs connected and listening at once.... the swf that connects to the socket first maintains priority until its closed... there for all requests for data by the second swf is ignored by the listener... I need to have multiple swfs make requests at virtually the same time and receive results back....  

Any help would be greatly appreciated.... below is what I have for the listener.

set_time_limit(100);

// Create the instance of the xml parse object //
$socket = socket_create( AF_INET , SOCK_STREAM , SOL_TCP);
   $isbind = socket_bind($socket, "10.10.0.103", 8787);
   if (!($isbind)){
      echo "Trouble Binding";
      return 0;
   }
   
   while($socket){
     socket_listen($socket, 10);
     $newsock = socket_accept($socket);
     $aSockets .= $newsock;
     $socketsCount = count($aSockets);
      if ($newsock){
          $indata = socket_read($newsock, 512);
          $xmlstring = $parse->parseinputxml("<xmls>" . $indata . "</xmls>",$xmlobject); //
          $string = "$xmlstring \0";
          socket_write($newsock, $string);
          socket_close($newsock);
      }else{
        echo "screwed up\n";
         
      }
 }
     
   socket_close($socket);
   echo "done\n";

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2002-12-17 at 11:47:34ID20429164
Tags

php

,

port

,

listener

Topic

PHP Scripting Language

Participating Experts
6
Points
500
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. php & xml
    hi there, Can anybody give me a sample coding for reading and displaying a XML file in php
  2. PHP and XML
    I have to report tomorrow morning on how PHP deals with XML. Is it good at handling XML / working with it. Pretend I am against it and convince me I should use PHP to deal with XML stuff. Thanks! Randy
  3. Is it possible to generate FLA files (not swf) from php
    Hi experts, As I know php quite well, I think once I'll get a lead, I'll get to the finish unharmed; however at this stage I am not even sure wether or not this can be done. For a personal tool I was wondering wether or not I can generate a fla file from flash. To have a c...
  4. How to encrypt by php and decrypt by swf?
    Hi ALL, How to encrypt by php and decrypt by swf and then encrypt by swf and decrypt by php? Please help

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: conner_bwPosted on 2002-12-17 at 11:54:30ID: 7597304

I'm not trying to discourage you in anyway, i hope you accomplish what you need, but are you aware of the new TinCan project by Macromedia?

http://www.macromedia.com/software/flashcom/

I worked with this a bit, and it definately does what you are asking, and more.

Not a PHP solution... But maybe something of value, regarldess.

Good Luck!

 

by: silpstreamPosted on 2002-12-17 at 23:51:16ID: 7599795

Is there a reason why you don't want to use the web server to wait and respond to the flash request. Your script could be set up to receive the request via HTTP GET or POST  or RAW POST and respond over the same path. You would still be able to retain session data and if needed you could pull this off on SSL for data encryption. Beyond that you would be taking advantage of a mature socket listener that is part of the web server. This could handle many multiples of your flash files connecting to it simultaneously.

 

by: silpstreamPosted on 2002-12-17 at 23:56:22ID: 7599816

Sorry one more thing to mention. If you aren't interested in the web server path, you might instead look towards using your current implementation and putting a wrapper around it such a xinetd or tcpwrap (I don't know what platform you are on). This should help by running of different instances for you as they service each request.

 

by: dewils80Posted on 2002-12-18 at 06:03:33ID: 7601092

Ok,
   I'm not going to start writing lots of code, simply because I haven't got enough time just now (pseudo code it is then):

The basic principle of your program must be:

----------------------------------------------
Create socket;
Bind socket;
Listen on socket;
do{
   accept connections
   if(connection_found){
      read off data from socket,
      pid = forkprocess;
      if(pid == child_process_pid){
         serve connection;
      }
   }
}while(true);
----------------------------------------------

In a nutshell, the server sit listening for a connection, as you have already done. But now, when it gets a connection, it reads the data and forks a new process. Find the process ID (PID) of the process you are in (obviously the two processes will find thier own PID), if it is the parent then continue round the loop looking for a connection...if it is the child it will serve the connection.

viola!

Dewils80

 

by: fetakPosted on 2002-12-19 at 07:07:59ID: 7607876

Hi...

 this is simple echo-reply asynchronous TCP server. It uses select insted of forking or multithreading. There are some drawbacks in this code but it is good example. You can test it using telnet or PuTTy or some other client providing raw socket connection.

 I hope this helps you...fell free to ask any related questions.

-fetak

And here is the source:
<?php

     // we want to see all errors
     error_reporting(E_ALL);
     
     // no time limit
     set_time_limit(0);
     
     // loading socket extension
     dl('php_sockets.dll');     // this was tested on win32

     // input, output, error streams "re"defs when we use
     // PHP version lower than 4.3.0
     if (version_compare(phpversion(), '4.3.0RC1', '<')) {
          define('STDIN', fopen("php://stdin","r"));
          define('STDOUT', fopen("php://stout","w"));
          define('STDERR', fopen("php://sterr","w"));
     }
     
     // server properties definition {{{
     // server address
     define('ADDR', '127.0.0.1');
     // server port
     define('PORT', 6666);
     // max clients in queue
     define('MAX_CLIENTS', 10);
     // }}}

     // create new AF_INET, SOCK_STREAM server
     @$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if (!$sock) {
          die(socket_strerror($sock)."\n");
     }

     // bind socket to appropriate address and port
     @$binded = socket_bind($sock, ADDR, PORT);
     if (!$binded) {
          die(socket_strerror($sock)."\n");
     }
     
     // make socket listening to incomming connections
     @$listening = socket_listen($sock, MAX_CLIENTS);
     if (!$listening) {
          die(socket_strerror($sock)."\n");
     }
     
     // non-blocking mode
     socket_set_nonblock($sock);
     
     // if true server will shutdown
     $stop_server = false;
     
     // list of active sockets
     $active_sockets = array(ADDR.':'.PORT => $sock);
     
     while (!$stop_server) {
          $r = $w = $e = $active_sockets;
          socket_select($r, $w, $e, 1);
         
          while (list($i, $curr_sock) = each($r)) {
               if ($curr_sock === $sock) {
                    fwrite(STDOUT, 'Accepting new connection...');
                    @$socket_accepted = socket_accept($sock);

                    if (!$socket_accepted) {
                         fwrite(STDOUT, "failed!\n");
                         break;
                    } else {
                         $c_addr = $c_port = 0;
                         socket_getpeername($socket_accepted, $c_addr, $c_port);
                         $active_sockets["$c_addr:$c_port"] = $socket_accepted;
                         fwrite(STDOUT, "accepted from $c_addr:$c_port($socket_accepted)\n");
                    }
               } else {
                    // read something here
                    @$data = trim(socket_read($curr_sock, 1024));
                    if ($data === '') {
                         $c_port = $c_addr = 0;
                         socket_getpeername($curr_sock, $c_addr, $c_port);
                         fwrite(STDOUT, "Client $c_addr:$c_port disconnected.\n");
                         socket_close($active_sockets["$c_addr:$c_port"]);
                         unset($active_sockets["$c_addr:$c_port"]);
                    } elseif ($data === '!stop') {
                         fwrite(STDOUT, "Server shutdown...");
                         $stop_server = true;
                    } else {
                         socket_write($curr_sock, "You wrote: $data\r\n");
                    }
               }
          }
     }
     
     fwrite(STDOUT, "done\n");
?>

 

by: phenixfilmsPosted on 2002-12-19 at 10:27:45ID: 7608916

Good answer ...

It works great for broadcasting to individual sockets but what about broadcasting to all sockets?  For instance  if the user enters anything but the letter 'n' it should broadcast to all sockets but 'n' should broadcast to the socket that sent it....  i dont mean if they typed in the word "gong show" that the n would be missing, i'm refering to individual characters at the moment.

Nathan.

 

by: fetakPosted on 2002-12-20 at 02:58:18ID: 7612718

 You can use $w array to broadcast to all sockets that are ready to accept data(are writeable).

  And if you don't want to read data terminated by \n or \r but as they come, you should add 3. argument to socket_read() function call wich should be PHP_BINARY_READ constant(this depends on PHP version you use, 'cause it is default value since PHP 4.1.0). This causes PHP to use system read() function. Data will be sent, and can be read, immidiately after they are written to socket and are binary safe too.

-fetak

 

by: fetakPosted on 2002-12-20 at 03:12:47ID: 7612757

 And to help you solve letter 'n' problem. You have to just remember which socket sent letter 'n'. And then resend it to the same socket. Sorry but I can not see any problem here :-) Maybe I misunderstood.

-fetak

 

by: ASCII_ManPosted on 2002-12-22 at 19:07:58ID: 7622413

@fetak
Stupid and arrogant comment:
Lines 35 to 38.
"bound" is more grammatically correct than "binded"
=P

 

by: fetakPosted on 2002-12-23 at 00:20:35ID: 7623134

ASCII_Man>>>
Yes I think your "bound" will solve his problem...mf

-fetak

 

by: fetakPosted on 2003-01-03 at 02:02:43ID: 7661215

phenixfilms>> You should accept one of my comments as answer :-) or are there any other problems concerning your question?

 

by: phenixfilmsPosted on 2003-03-25 at 15:05:27ID: 8206714

Wonderful answer. It has helped a complete project to be developed. Simply incredible... sorry for the delay in saying so, but hey i was busy implementing the system.

Way to go.

 

by: molikjainPosted on 2010-09-24 at 00:17:19ID: 33751602

Hi Fetak

Can you help me with the same script above.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...