Implementation code for php and java to communicate via socket

  • 2020-10-07 18:36:11
  • OfStack

The simple function of demo is to take the string written by the PHP side and return it to the output as is. The code is 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"); 
              } 
        } 
}

The java program will listen to port 5678 in the future. When the message is received, it will return the received message to the client as it is...
The code for PHP is 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 ); 
    // Send data to the server  
    socket_write ( $socket, 'Hello' . "\n" ); 
    // Accept server return data  
    $str = socket_read ( $socket, 1024, PHP_NORMAL_READ ); 

    echo $str; 
    // Shut down  
    socket_close($socket);

The PHP program connects to port 5678 of the machine, writes to Hello, and then reads the returned data... Output the returned data to the browser...
Run the server side of java, then visit the PHP page with your browser and you will see the Hello returned from the server side


Related articles: