demo實現的簡單功能是,接受PHP端寫入的字符串,然後原樣返回給輸出端。代碼如下:
復制代碼 代碼如下:
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");
}
}
}
運行起來,以後該java程序將監聽5678端口,當接收到消息以後,將接收的消息原樣返回給客戶端……
PHP的代碼如下:
復制代碼 代碼如下:
<?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 );
//向服務端發送數據
socket_write ( $socket, 'Hello' . "\n" );
//接受服務端返回數據
$str = socket_read ( $socket, 1024, PHP_NORMAL_READ );
echo $str;
//關閉
socket_close($socket);
PHP程序連接本機的5678端口,寫入 Hello,然後讀取返回的數據……將返回的數據,輸出到浏覽器……
先運行起java的服務端,然後用浏覽器訪問PHP頁面,將看到從服務器端返回的Hello