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
更多php與java透過socket通訊的實作程式碼相關文章請關注PHP中文網!