|
demo實(shí)現(xiàn)的簡(jiǎn)單功能是,接受php端寫入的字符串,然后原樣返回給輸出端。代碼如下:
復(fù)制代碼 代碼如下:
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");
}
}
}
運(yùn)行起來,以后該Java程序?qū)⒈O(jiān)聽5678端口,當(dāng)接收到消息以后,將接收的消息原樣返回給客戶端……
php的代碼如下:
復(fù)制代碼 代碼如下:
<?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 );
//向服務(wù)端發(fā)送數(shù)據(jù)
socket_write ( $socket, 'Hello' . "/n" );
//接受服務(wù)端返回?cái)?shù)據(jù)
$str = socket_read ( $socket, 1024, php_NORMAL_READ );
echo $str;
//關(guān)閉
socket_close($socket);
php程序連接本機(jī)的5678端口,寫入 Hello,然后讀取返回的數(shù)據(jù)……將返回的數(shù)據(jù),輸出到瀏覽器……
先運(yùn)行起Java的服務(wù)端,然后用瀏覽器訪問php頁面,將看到從服務(wù)器端返回的Hello
php技術(shù):php與java通過socket通信的實(shí)現(xiàn)代碼,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。