Home >Java >javaTutorial >Example tutorial on communication between java and php through socket

Example tutorial on communication between java and php through socket

PHP中文网
PHP中文网Original
2017-05-27 09:38:262375browse

The simple function implemented by

demo is to accept the string written by the PHP end, and then return it to the output end as it is. The code is as follows:

The code is as follows:

import java.io.*; 
import java.net.*; 
public 
class
 Server { 
public 
static
 void 
main
(
String
[] args) throws IO
Exception
{ 
  System.out.
print
ln("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"); 
              } 
        } 
}

After running, the java program will listen to the 5678 port. When the message is received, the received message will be returned to the client as it is...
The PHP code is as follows:

The code is as follows:

<?php 
    $socket = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP ) or die ( &#39;could not create socket&#39; ); 
    $connect = socket_connect ( $socket, &#39;127.0.0.1&#39;, 5678 ); 
    //向服务端发送数据 
    socket_write ( $socket, &#39;Hello&#39; . "\n" ); 
    //接受服务端返回数据 
    $str = socket_read ( $socket, 1024, PHP_NORMAL_READ ); 
    
echo
 $str; 
    //关闭 
    socket_close($socket);

The PHP program connects to the 5678 port of the local machine, writes Hello, and then reads the returned data...will return Data is output to the browser...
First run the java server, and then use the browser to access the PHP page. You will see the Hello returned from the server

[Related recommendations]

1. Detailed explanation of the valueOf method example in java

2. Share the example code in java that handles sticky packets during socket communication

3. Java instance-ServerSocket and Socket communication instance

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn