Php tcp/UDP network client class (W/example)

Source: Internet
Author: User
Tags socket blocking

Http://www.codewalkers.com/c/a/Miscellaneous-Code/PHP-TCP-UDP-Network-Client-Class-w-Example/
----------------------------------------
<! -- Example script using class -->
<Font face = "verdana" size = "2">
<?
Include ('class. tcpclient. php ');

// ** Displays the error message given if there is non-empty text.

Function showerror ($ errortext)
{
If (strlen ($ errortext)> 0)
Print ("<font color = 'red'> $ errortext </font> <br> ");
}
// ** The POP server address, user account, and password to use
// ** Testing client application. Note: Your pop user name is your
// ** Full email address, unless the server is otherwise configured.

$ Popserver = "popserver.yourdomain.com ";
$ Popuser = "email@yourdomain.com ";
$ Poppassword = "yourpassword ";

// ** Connect to the POP server given on 110, the standard POP port.
// ** Change this if necessary.

$ Client = new tcpclient ($ popserver, 110 );

// ** Set the default read/write timeout to 2 seconds (2000 MS ).

$ Client-> timeout = 2000;

// ** You can set the default newline character (s) used when sending data.

$ Client-> newline = "/R/N ";

// ** Connect to server and get any error message (if available ).

$ Client-> connect ();
Showerror ($ client-> geterror ());

// ** Get the MailServer greeting (one line ).

Print ("<B>". $ client-> Readline (). "</B> <br> ");
Showerror ($ client-> geterror ());

// ** Send user login info to the server.

Print ($ client-> writeline ("User $ popuser"). "bytes written <br> ");
Showerror ($ client-> geterror ());

// ** Get the MailServer user response message.

Print ("<B>". $ client-> Readline (). "</B> <br> ");
Showerror ($ client-> geterror ());

// ** Send user account password to the server.

Print ($ client-> writeline ("pass $ poppassword"). "bytes written <br> ");
Showerror ($ client-> geterror ());

// ** Get the MailServer pass response message, login success

Print ("<B>". $ client-> Readline (). "</B> <br> ");
Showerror ($ client-> geterror ());

//**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//**
// ** Put any other commands for the POP server here!
// ** Full command list @ http://www.ietf.org/rfc/rfc1939.txt
//**
//**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!

// ** Handle y the mail server connection is closing.

Print ($ client-> writeline ("quit"). "bytes written <br> ");
Showerror ($ client-> geterror ());

// ** Get the MailServer farewell message.

Print ("<B>". $ client-> Readline (). "</B> <br> ");
Showerror ($ client-> geterror ());

$ Client-> close ();
?>
</Font>

<?
// -- Class file for tcp client --
// ** Ã ‚ â William Fowler (wmfwlr@cogeco.ca)
// ** December 22/2003, Version 1.0

If (isset ($ globals ["tcpclientclass_php"]) {return;} // ** include once.
$ Globals ["tcpclientclass_php"] = 1; // ** file encoded ded.

// ** Error code indicating that no connection is available.

Define ("tcpclientnoconnection", 0 );

// ** The default number of milliseconds to wait before timing out.

Define ("tcpclientdefaulttimeout", 30000 );

// ** The minimum buffer size for the tcp client class.

Define ("tcpclientminbuffersize", 256 );

// ** The default newline character (s) used.

Define ("tcpclientnewline", "/R/N ");

//**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// ** Tcp_client_class_definition *********************************** ************
// ** The tcpclient class encapsulates most networking communication details
// ** Into an easy-to-use wrapper. connections are not persistant.

Class tcpclient
{
// ** (Integer) the internal underlying socket identifier.

VaR $ socket = tcpclientnoconnection;

// ** (String) the name/IP of the remote host

VaR $ host;

// ** (Integer) the port number to connect to remote host.

VaR $ Port = 0;

// ** (String) The last error that occurred (null if no error ).

VaR $ lasterror = NULL;

// ** (String) The newline character to be used when sending data.

VaR $ newline = tcpclientnewline;

// ** (Integer) The size of the buffer used to receive data.

VaR $ receivebuffersize = tcpclientminbuffersize;

// ** (Integer) the number of milliseconds to wait before aborting a connect,
// ** Read, or write operation for the client.

VaR $ timeout = tcpclientdefadefatimeout;

// ** Creates a new tcpclient instance based on the hostname and port given.

Function tcpclient ($ remotehost = NULL, $ portnum = 0)
{
$ This-> host = strval ($ remotehost );
$ This-> Port = intval (max (0, $ portnum); // ** ensure port> = than zero.
}
// ** Returns: Boolean
// ** Determine whether or not a connection to the remote host has been
// ** Established.

Function isopen ()
{
Return ($ this-> socket? True: false );
}
// ** Returns: String
// ** Get the last recorded error that occurred. If no error previusly
// ** Occurred null is returned. The last error is cleared.

Function geterror ()
{
$ Theerror = $ this-> lasterror;
$ This-> clearerror ();
Return $ theerror;
}
// ** Returns: None
// ** Clear the last error stored for this client.

Function clearerror ()
{
$ This-> lasterror = NULL;
}
// ** Returns: Boolean
// ** Attemept to connect to the client remote host on the port number given.
// ** If no host is available false is returned and no connection is made.
// ** If false is returned the last error is available from the 'geterror ()'
// ** Method.

Function connect ()
{
$ This-> clearerror (); // ** clear any existing error messages.

// ** No host name/IP has been set for this client, no connection can be made.
// ** Store the appropriate error.

If (strlen (TRIM ($ this-> host) = 0)
{
$ This-> lasterror = "no remote host was provided ";
Return false;
}
// ** Attempt to connect to the host on the port given. Record any error number
// ** And error message generated.

$ Errornum = 0;
$ This-> socket = fsockopen ($ this-> host, $ this-> port, & $ errornum,
& $ This-> lasterror, ($ this-> time out/1000 ));

// ** If there is no error given and the socket is valid connection is okay.

Return ($ this-> isopen () & strlen (TRIM ($ this-> lasterror) = 0 );
}
// ** Returns: Boolean
// ** Attempt to close the open client connection.

Function close ()
{
// ** No open cobnnection is available. Set error appropriately.

If (! $ This-> isopen ())
$ This-> lasterror = "no connection available to close ";

// ** An open connection is available to close. Close underlying socket.

Else
{
Fclose ($ this-> socket); // ** clsoe the connection.
$ This-> socket = tcpclientnoconnection; // ** no connection now.
}
Return! $ This-> isopen (); // ** return the close operation success.
}
// ** Returns: integer
// ** Attempt to write the data given to the underlying socket. The number
// ** Bytes successfully written to the stream is returned. If no connection
// ** Is available 0 is returned, as no Bytes were written.

Function write ($ DATA = NULL)
{
// ** No connection is available, zero bytes can be sent.

If (! $ This-> isopen ())
{
$ This-> lasterror = "no connection available for writing ";
Return 0;
}
$ DATA = strval ($ data); // ** ensure that data is available.
If (strlen ($ data) = 0) // ** no data to be sent.
Return 0; // ** zero bytes were sent.
Else // ** connection and data, set timeout and send.
{
$ This-> _ setTimeout (); // ** set timeout.
Return fwrite ($ this-> socket, $ data, strlen ($ data); // ** write data.
}
}
// ** Returns: integer
// ** Attempt to write the data given to the underlying socket, followed by
// ** Newline. The newline is defined by the '$ this-> newline' property.
// ** Number of bytes actually written is returned.

Function writeline ($ DATA = NULL)
{
Return $ this-> write ($ data. $ this-> newline );
}
// ** Returns: String
// ** Attempt to read the number of bytes given (or one by default) from
// ** Connection. If no connection is available, the length given is zero or
// ** Negative, or an error occurs null is returned.

Function read ($ length = 1)
{
If (intval ($ length) <= 0)
{
$ This-> lasterror = "cannot read zero or less bytes ";
Return NULL;
}
// ** No connection is available to read from, no data can be read.

Else if (! $ This-> isopen ())
{
$ This-> lasterror = "no connection available for reading ";
Return NULL;
}
Else // ** a valid connection identifier is available.
{
$ This-> _ setTimeout (); // ** ensure timeout is set.
Return fread ($ this-> socket, $ length); // ** attempt to read N-bytes.
}
}
// ** Returns: String
// ** Attempt to read one full line from the underlying stream. If no
// ** Connection is available null is returned. Any newline characters
// ** Are encoded in the string returned.

Function Readline ()
{
// ** No connection is available to read from, no data can be read.

If (! $ This-> isopen ())
{
$ This-> lasterror = "no connection available for reading ";
Return NULL;
}
// ** Continue to read in data until a line ends with the newline character (s ).
// ** This is safe as the 'fgets () 'function will not read past a newline
// ** Character. Ensure that the read buffer is at least the minumum size. If
// ** One iteration is complete and no data was read in the socket Blocking
// ** Expired. Stop reading at that point.

$ Streamdata = ""; // ** no data to start.
$ Sockethasexpired = false; // ** initially no timeout experienced.

While (! $ This-> _ endswithnewline ($ streamdata )&&! $ Sockethasexpired)
{
$ This-> _ setTimeout (); // ** ensure socket timeout is set.

$ Streamdata. = fgets ($ this-> socket, max (tcpclientminbuffersize,
$ This-> receivebuffersize ));

// ** If ever at the point where reading has occurred and no data is available
// ** A socket timeout has occurred. Exit the loop and set the error.

If (strlen ($ streamdata) = 0)
{
$ Sockethasexpired = true;
$ This-> lasterror = "The read took longer than $ this-> timeout ms ";
}
}
Return $ streamdata; // ** return the data encoded ed, including newline.
}
// ** Returns: Boolean
// ** Determine whether or not the string given ends with a newline character.
// ** If no data is given false is returned.

Function _ endswithnewline ($ DATA = NULL)
{
$ DATA = strval ($ data); // ** ensure that data is a string.
If (strlen ($ data) = 0) // ** no date given to test.
Return false; // ** does not end with newline.

// ** Get the position of the last newline character. If the value returned
// ** Is not numeric it is a Boolean, indicating no match. considered to end
// ** With newline if it ends with either A'/N' or '/R' character.

$ Creturnpos = strrpos ($ data, "/R"); // ** position of '/N '.
$ Newlinepos = strrpos ($ data, "/N"); // ** position of '/R '.

Return (is_int ($ newlinepos) | is_int ($ creturnpos ));
}
// ** Returns: None
// ** Set the underlying socket timeout to the 'timeout' value for this
// ** Instance. If not connected nothing is done.

Function _ setTimeout ()
{
// ** If a connection is available set the socket timeout. Get the number
// ** Seconds and microseconds form the instance 'timeout' property.

If ($ this-> isopen ())
{
Stream_set_timeout ($ this-> socket, intval ($ this-> timeout/1000 ),
Intval ($ this-> timeout % 1000) * 1000 ));
}
}
}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.