思路:啓用一個java監聽socket線程 採用的是udp而不是tcp。而後使用php socket根據ip推送過去。php
java程序html
class ReciveThread extends Thread { public void run() { while (true) { DatagramSocket ds = null; byte[] buf = new byte[1024]; DatagramPacket dp = null; try { ds = new DatagramSocket(9000);// 打開端口 } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } dp = new DatagramPacket(buf, 1024); try { ds.receive(dp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 若是有消息 彈出框 String str = new String(dp.getData(), 0, dp.getLength()) + "from" + dp.getAddress().getHostAddress() + ":port" + dp.getPort(); ts(str); ds.close(); } } }
php push到java監聽java
<?php /** * 重點參考http://www.cnblogs.com/xiaowu/archive/2012/09/18/2690677.html * Enter description here ... * @author Administrator * */ class SocketPush { public $ip = array( '10.1.1.106', '10.1.1.177', '10.1.1.200', '10.1.1.128'); public $port = 9000; /*推送功能 採用UDP協議*/ public function push($msg) { $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); $len = strlen($msg); for ($i = 0; i < count($this->ip); $i ++) { @socket_sendto($sock, $msg, $len, 0, $this->ip[$i], $this->port); } socket_close($sock); } }