Help getting a socket to work?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Martin

    Help getting a socket to work?

    I am a PHP newbie (just got my "Hello World" page working this
    morning). I'm doing some R&D work to see if PHP is viable for a
    situation I have. To accomplish what I want to do, I have to have the
    PHP page communicate directly with another process.

    I want the PHP script to establish a socket connection to the other
    process, send a message and receive some data back which would then
    used for calculations and/or display on the resulting page. The PHP
    page will be the client - the other process will be the server. The
    server process is a program that I've written using Visual Basic 6 and
    the socket there is the standard Winsock that's part of VB.

    Shown below is the entire page that I'm using to test this concept;
    I've adapted it from an example provided in the "Socket Functions"
    section of the manual on the PHP.net website. Amazingly enough, this
    actually works - up to a point. I'm hoping someone here can help get
    it working all the way through.

    This script works up to the point of reading the response. It creates
    the connection (my server process accepts the connection and receives
    the "Hello world" message). The server sends its message. But then the
    script seems to just sit there - it doesn't complete - it doesn't
    generate any output.

    Can anyone suggest what I might need to do to get this to work?

    If it matters, I'm using PHP 5.0.1, IIS 5.1 running on Windows XP with
    service pack 2.

    Thanks


    -----------------------------------------------------------------------------------
    <HTML>
    <BODY>

    <?php
    echo "<h2>TCP/IP Connection</h2>\n";

    $service_port = 1001;
    $address = "192.168.200.19 ";

    $socket = socket_create(A F_INET, SOCK_STREAM, SOL_TCP);
    if ($socket < 0) {
    echo "socket_create( ) failed: reason: " . socket_strerror ($socket)
    .. "<br>";
    } else {
    echo "OK.<br>";
    }

    echo "Attempting to connect to '$address' on port '$service_port' ...";
    $result = socket_connect( $socket, $address, $service_port);
    if ($result < 0) {
    echo "socket_connect () failed.\nReason : ($result) " .
    socket_strerror ($result) . "<br>";
    } else {
    echo "OK.<br>";
    }

    $in = "Hello World";
    $out = "";

    echo "Sending message...";
    socket_write($s ocket, $in, strlen($in));
    echo "OK.<br>";

    echo "Reading response: <br><br>";
    while ($out = socket_read($so cket, 999, PHP_NORMAL_READ )) {
    echo $out;
    }

    echo "<br>Closin g socket...";
    socket_close($s ocket);
    echo "OK.<br><br >";

    ?>

    </BODY>
    <HTML>
  • Andy Hassall

    #2
    Re: Help getting a socket to work?

    On Thu, 02 Sep 2004 15:40:13 -0700, Martin <martinvalley@c omcast.net> wrote:
    [color=blue]
    >This script works up to the point of reading the response. It creates
    >the connection (my server process accepts the connection and receives
    >the "Hello world" message). The server sends its message. But then the
    >script seems to just sit there - it doesn't complete - it doesn't
    >generate any output.[/color]

    What does the server do after it's sent "Hello world"?

    Does it follow this with a \n (since you're using the PHP_NORMAL_READ option
    which claims to stop reading when it hits \r or \n), or close the connection?

    If it doesn't do either of those, your script is probably just waiting for the
    server to send some more data (you asked for 999 bytes).

    --
    Andy Hassall / <andy@andyh.co. uk> / <http://www.andyh.co.uk >
    <http://www.andyhsoftwa re.co.uk/space> Space: disk usage analysis tool

    Comment

    • Daniel Tryba

      #3
      Re: Help getting a socket to work?

      Martin <martinvalley@c omcast.net> wrote:[color=blue]
      > This script works up to the point of reading the response. It creates
      > the connection (my server process accepts the connection and receives
      > the "Hello world" message). The server sends its message. But then the
      > script seems to just sit there - it doesn't complete - it doesn't
      > generate any output.[/color]

      Are you sure it stops at the read? You are not checking if the write
      succeeds. Have you used a packetsniffer to find out whats really going
      on?
      [color=blue]
      > Can anyone suggest what I might need to do to get this to work?
      >
      > If it matters, I'm using PHP 5.0.1, IIS 5.1 running on Windows XP with
      > service pack 2.[/color]

      Mayeb you found another program that is broken by SP2 :)
      [color=blue]
      > echo "Reading response: <br><br>";
      > while ($out = socket_read($so cket, 999, PHP_NORMAL_READ )) {
      > echo $out;
      > }[/color]


      This blocks untill:
      - 999 bytes are read.
      - a \n, \r or \0 is received

      Are these conditions met?

      BTW why socket_* and not fsockopen?

      --

      Daniel Tryba

      Comment

      • Martin

        #4
        Re: Help getting a socket to work?

        Andy / Daniel -

        Thanks.
        [color=blue]
        >Mayeb you found another program that is broken by SP2 :)[/color]

        yeah, very well could be.
        [color=blue]
        >[color=green]
        >> echo "Reading response: <br><br>";
        >> while ($out = socket_read($so cket, 999, PHP_NORMAL_READ )) {
        >> echo $out;
        >> }[/color]
        >
        >
        >This blocks untill:
        >- 999 bytes are read.
        >- a \n, \r or \0 is received
        >
        >Are these conditions met?[/color]

        No, they weren't. I didn't know I needed to do that. When I added \n
        to the message from the server, the script started working all the way
        through. However, I'm still getting an error on the socket_read. It
        says: "unable to read from socket. operation completed successfully."

        I tried taking the socket_read out of the "while" construct but it
        didn't make any difference.

        I found a comment on the PHP.net site that said that socket_read
        doesn't work in Windows (the comment is nearly a year old). The writer
        says to use: socket_recv instead. I tried it thus:

        $rcd=socket_rec v($socket,$buff er,999,0);
        echo $rcd;
        echo "<br>" . $buffer;

        It worked!

        Howeer, this appears to NOT wait on any terminating character. Since
        it's possible for tcp/ip to break up the messages, I'm concerned that
        I'll always receive complete messages. (I've had problems with that in
        the past).

        [color=blue]
        >BTW why socket_* and not fsockopen?[/color]

        Because I don't know any better. Should I be using it?

        Any other advice and guidance will be greatly appreciated.

        Thanks again.

        Comment

        • Daniel Tryba

          #5
          Re: Help getting a socket to work?

          Martin <martinvalley@c omcast.net> wrote:[color=blue][color=green]
          >>Mayeb you found another program that is broken by SP2 :)[/color]
          >
          > yeah, very well could be.[/color]

          It did remove atleast some socket support (raw IIRC).

          [...][color=blue]
          > $rcd=socket_rec v($socket,$buff er,999,0);
          > echo $rcd;
          > echo "<br>" . $buffer;
          >
          > It worked!
          >
          > Howeer, this appears to NOT wait on any terminating character. Since
          > it's possible for tcp/ip to break up the messages, I'm concerned that
          > I'll always receive complete messages. (I've had problems with that in
          > the past).[/color]

          Huh? I guess you mean incomplete messages? You'll have to play with
          timeouts and blocking mode...
          [color=blue][color=green]
          >>BTW why socket_* and not fsockopen?[/color]
          >
          > Because I don't know any better. Should I be using it?[/color]

          http://www.php.net/manual/en/ref.sockets.php says:
          This extension is EXPERIMENTAL. The behaviour of this extension --
          including the names of its functions and anything else documented about
          this extension -- may change without notice in a future release of PHP.
          Use this extension at your own risk.

          And since you are using a plain tcp socket, you might as wel use the
          proven methods, which are fsockopen(), feof(), fread/fwrite,
          fgets/fputs. Your program would roughly be (no error handling):

          <?php
          $s=fsockopen($a ddress, $service_port);

          fwrite($s,"Hell o World");
          while(!feof($s) )
          {
          echo fgets($s,999);
          }
          fclose($fp);
          ?>

          --

          Daniel Tryba

          Comment

          • Pjotr Wedersteers

            #6
            Re: Help getting a socket to work?

            Martin wrote:[color=blue]
            > I am a PHP newbie (just got my "Hello World" page working this
            > morning). I'm doing some R&D work to see if PHP is viable for a
            > situation I have. To accomplish what I want to do, I have to have the
            > PHP page communicate directly with another process.
            >
            > I want the PHP script to establish a socket connection to the other
            > process, send a message and receive some data back which would then
            > used for calculations and/or display on the resulting page. The PHP
            > page will be the client - the other process will be the server. The
            > server process is a program that I've written using Visual Basic 6 and
            > the socket there is the standard Winsock that's part of VB.
            >
            > Shown below is the entire page that I'm using to test this concept;
            > I've adapted it from an example provided in the "Socket Functions"
            > section of the manual on the PHP.net website. Amazingly enough, this
            > actually works - up to a point. I'm hoping someone here can help get
            > it working all the way through.
            >
            > This script works up to the point of reading the response. It creates
            > the connection (my server process accepts the connection and receives
            > the "Hello world" message). The server sends its message. But then the
            > script seems to just sit there - it doesn't complete - it doesn't
            > generate any output.
            >
            > Can anyone suggest what I might need to do to get this to work?
            >
            > If it matters, I'm using PHP 5.0.1, IIS 5.1 running on Windows XP with
            > service pack 2.
            >
            > Thanks
            >
            >
            > --------------------------------------------------------------------------[/color]
            ---------[color=blue]
            > <HTML>
            > <BODY>
            >
            > <?php
            > echo "<h2>TCP/IP Connection</h2>\n";
            >
            > $service_port = 1001;
            > $address = "192.168.200.19 ";
            >
            > $socket = socket_create(A F_INET, SOCK_STREAM, SOL_TCP);
            > if ($socket < 0) {
            > echo "socket_create( ) failed: reason: " . socket_strerror ($socket)
            > . "<br>";
            > } else {
            > echo "OK.<br>";
            > }
            >[/color]
            By the way, you can use this construction as well for testing and stuff, as
            many of the PHP functions return FALSE when failed.
            Very common, easier to maintain too.

            $socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) or die
            socket_strerror ($socket);
            echo "OK <br>";


            Comment

            • Daniel Tryba

              #7
              Re: Help getting a socket to work?

              Pjotr Wedersteers <x33159@westert erp.com> wrote:[color=blue]
              > By the way, you can use this construction as well for testing and stuff, as
              > many of the PHP functions return FALSE when failed.
              > Very common, easier to maintain too.
              >
              > $socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) or die
              > socket_strerror ($socket);
              > echo "OK <br>";[/color]

              While this example might (accidentally) work for socket_create. Consider
              the following example when trying to handle false.

              $hay="foo bar";
              $needle="foo";

              if(strpos($hay, $needle)==false )
              {
              die("Fatal error: '$hay' doens't contain '$needle'");
              }


              vs.

              if(strpos($hay, $needle)===fals e)
              {
              die("Fatal error: '$hay' doens't contain '$needle'");
              }

              Moral: if you know what type the return value should be, check for type
              as well.


              --

              Daniel Tryba

              Comment

              • Martin

                #8
                Re: Help getting a socket to work?

                On Fri, 3 Sep 2004 01:42:36 +0000 (UTC), Daniel Tryba
                <news_comp.lang .php@canopus.nl > wrote:
                [color=blue][color=green]
                >> Howeer, this appears to NOT wait on any terminating character. Since
                >> it's possible for tcp/ip to break up the messages, I'm concerned that
                >> I'll always receive complete messages. (I've had problems with that in
                >> the past).[/color]
                >
                >Huh? I guess you mean incomplete messages? You'll have to play with
                >timeouts and blocking mode...[/color]

                Yes, I meant *incomplete* messages. In my work with socket
                communications, I've always used delimiters at both ends of the
                messages. On the receiving end, I then build a string of received data
                until I see the termination character at which point I do whatever
                processing that needs to be done.

                <snip>
                [color=blue]
                >And since you are using a plain tcp socket, you might as wel use the
                >proven methods, which are fsockopen(), feof(), fread/fwrite,
                >fgets/fputs. Your program would roughly be (no error handling):
                >
                ><?php
                >$s=fsockopen($ address, $service_port);
                >
                >fwrite($s,"Hel lo World");
                >while(!feof($s ))
                >{
                > echo fgets($s,999);
                >}
                >fclose($fp);
                >?>[/color]

                Thanks for the example.

                Do you know if this works in Windows? I have not been able to get it
                to work. PHP.net gives a very similar example but I simply cannot get
                it to receive any data. I've added a bunch of error handling - I know
                the socket is opening ok and it's sending the request message to my
                other process. The other process is sending its response (I've tried
                both terminated and non-terminated). No luck.

                Any suggestions?

                Thanks.

                Comment

                Working...