思路:启用一个java监听socket线程 采用的是udp而不是tcp。然后使用php socket根据ip推送过去。
java程序
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监听
<?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);
}
}