The implementation code _php instance of PHP and Java through socket communication

Source: Internet
Author: User

The simple feature of the demo implementation is to accept the string written by the PHP side and return it to the output. The code is as follows:

Copy Code code as follows:



import java.io.*;


import java.net.*;





public class Server {


public static void Main (string[] args) throws ioexception{


System.out.println ("Server started!\n");


serversocket server=new ServerSocket (5678);


while (true) {


Socket client=server.accept ();


System.out.println ("Client coming!\n");


PrintWriter printer = new PrintWriter (Client.getoutputstream ());


BufferedReader reader = new BufferedReader (New InputStreamReader (Client.getinputstream ()));


String m = Reader.readline ();


System.out.println ("Get infomation" + M + "\ n from" + client.getinetaddress (). toString ());


printer.println (m);


Printer.flush ();


Printer.close ();


Printer.close ();


Client.close ();


System.out.println ("Client leaving!\n");


              }


        }


}


Run, the Java program will listen to Port 5678, and when the message is received, return the received message to the client ...
The code for PHP is as follows:

Copy Code code as follows:

<?php
$socket = Socket_create (Af_inet, Sock_stream, sol_tcp) or die (' could not create socket ');
$connect = Socket_connect ($socket, ' 127.0.0.1 ', 5678);
Sending data to the server
Socket_write ($socket, ' Hello '. "\ n");
Accept service-side return data
$str = Socket_read ($socket, 1024, php_normal_read);

Echo $str;
Shut down
Socket_close ($socket);

The PHP program connects the local 5678 port, writes Hello, and reads the returned data ... Output the returned data to the browser ...
Run the Java server first, and then use the browser to access the PHP page, you will see the return of the Hello

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.