www-thermferm/socketmessage.php

Thu, 10 Jul 2014 11:46:27 +0200

author
Michiel Broek <mbroek@mbse.eu>
date
Thu, 10 Jul 2014 11:46:27 +0200
changeset 98
6e7e69f3493a
permissions
-rw-r--r--

Start over again with web pages

<?php
/*****************************************************************************
 * Copyright (C) 2014
 *   
 * Michiel Broek <mbroek at mbse dot eu>
 *
 * This file is part of ThermFerm
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * ThermFerm is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ThermFerm; see the file COPYING.  If not, write to the Free
 * Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 *****************************************************************************/

function open_socket()
{
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    if (!($sock === false)) {
	if (socket_connect($sock, "localhost", 6554)) {
	    socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 15, 'usec' => 0));
	} else {
	    socket_close($sock);
    	}
    }
    return $sock;
}



function startsWith($haystack, $needle)
{
    return !strncmp($haystack, $needle, strlen($needle));
}



error_reporting(E_ALL ^ E_WARNING);
if(isset($_POST['messageType'])){
    $messageType = $_POST['messageType'];
} else {
    die("messageType not set");
}



if(isset($_POST['message'])){
    // message with data
    $data = $_POST['message'];
}



$sock = open_socket();
if ($sock !== false) {
    if (isset($data) && $data != "") {
	socket_write($sock, $messageType . " " . $data, 4096);
    } else {
	socket_write($sock, $messageType, 4096);
    }

    /*
     * Multiple reads until the remote closed the connection
     */
    $answer = "";
    while (1) {
	$line = socket_read($sock, 4096);
	if ($line === '')
	    break;
	$answer .= $line;
    }

    /*
     * Can be a multiline answer, the answer includes \r\n sequences.
     */
    echo $answer;
    socket_close($sock);
}

mercurial