PHP Java Socket Communication

Source: Internet
Author: User
PHP Java Socket Communication

Java writes the NIO Socket server side and needs to send commands past the page written from PHP.

?

Java Socket Server main code:

public static void Main (String args[]) {
?? System.out.println ("Start Server ...");
?? try {
??? ServerSocket Server = new ServerSocket (8083);
??? while (true) {
???? Socket client = Server.accept ();
???? System.out.println (Client.getinetaddress (). toString ());
???? BufferedReader br = new BufferedReader (New InputStreamReader (Client.getinputstream ()));
???? PrintWriter pw = new PrintWriter (Client.getoutputstream (), true);
???? String m = Br.readline ();? \ \ Because this is called the ReadLine () method, the default read \ n is executed. So add \ n at the end of the value passed by the PHP client. Otherwise the code will stop in this line and not execute down.
???? System.out.println ("Client Message:" + M);
???? System.out.println ("Client IP:" + client.getinetaddress (). toString ());
???? Pw.write ("Hello, I am from Java Server");
???? Pw.flush ();
???? Pw.close ();
???? Br.close ();
???? Client.close ();
????
????
???}
??} catch (IOException e) {
??? TODO auto-generated Catch block
??? E.printstacktrace ();
??}
?}

?

?

?

PHP page Send request:

? $socket = socket_create (af_inet,sock_stream,sol_tcp) or Die (' Could does Connect to socket ');
Socket_set_option ($socket, Sol_socket,so_rcvtimeo,array ("SEC" =>1, "USEC" =>0));

$connect = Socket_connect ($socket, ' 10.50.70.195 ', 8083);
$output = Iconv ("Utf-8", "GBK", "This was from message\n");
Socket_write ($socket, $output, strlen ($output));

This line of comment? $str = Socket_read ($socket, 1024,php_normal_read); If you add Php_normal_read, the PHP client cannot read the value returned by the server side. and error: [Function.socket-read]: Unable to read from socket [0]: ....
$str = Socket_read ($socket, 1024);
Echo $str;
Socket_close ($socket);

?>

?

?

?

?

  • 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.