/*
* 凯发天生赢家一触即发官网 copyright (c) 2016 即时通讯网(52im.net) - 即时通讯开发者社区.
* all rights reserved.
*/
package
net.x52im.example.android.udp;
import
java.net.datagrampacket;
import
java.net.datagramsocket;
import
net.x52im.example.android.udp.utils.configentity;
import
android.content.context;
import
android.util.log;
/**
* 本地udp端口监听和数据接收类。
*
* @author jack.jiang@52im.net, 2016-06-27
* @version 1.0
*/
public
class
localudpdatareciever
{
private
static
final
string tag = localudpdatareciever.
class
.getsimplename();
private
static
localudpdatareciever instance =
null
;
private
thread thread =
null
;
private
context context =
null
;
public
static
localudpdatareciever getinstance(context context)
{
if
(instance ==
null
)
instance =
new
localudpdatareciever(context);
return
instance;
}
private
localudpdatareciever(context context)
{
this
.context = context;
}
public
void
startup()
{
this
.thread =
new
thread(
new
runnable()
{
public
void
run()
{
try
{
log.d(localudpdatareciever.tag,
"本地udp端口侦听中,端口="
configentity.localudpport
"..."
);
//开始侦听
localudpdatareciever.
this
.udplisteningimpl();
}
catch
(exception eee)
{
log.w(localudpdatareciever.tag,
"本地udp监听停止了(socket被关闭了?),"
eee.getmessage(), eee);
}
}
});
this
.thread.start();
}
private
void
udplisteningimpl()
throws
exception
{
while
(
true
)
{
byte
[] data =
new
byte
[
1024
];
// 接收数据报的包
datagrampacket packet =
new
datagrampacket(data, data.length);
datagramsocket localudpsocket = localudpsocketprovider.getinstance().getlocaludpsocket();
if
((localudpsocket ==
null
) || (localudpsocket.isclosed()))
continue
;
// 阻塞直到收到数据
localudpsocket.receive(packet);
// 解析服务端发过来的数据
string pfromserver =
new
string(packet.getdata(),
0
, packet.getlength(),
"utf-8"
);
log.w(localudpdatareciever.tag,
"【note】>>>>>> 收到服务端的消息:"
pfromserver);
}
}
}