public
class
movementeventsource
implements
eventsource {
private
int
width =
800
;
private
int
height =
600
;
private
int
stepmax =
5
;
private
int
x =
0
;
private
int
y =
0
;
private
random random =
new
random();
private
logger logger = logger.getlogger(getclass().getname());
public
movementeventsource(
int
width,
int
height,
int
stepmax) {
this
.width = width;
this
.height = height;
this
.stepmax = stepmax;
this
.x = random.nextint(width);
this
.y = random.nextint(height);
}
@override
public
void
onopen(emitter emitter)
throws
ioexception {
query(emitter);
//开始生成位置信息
}
@override
public
void
onresume(emitter emitter, string lasteventid)
throws
ioexception {
updateposition(lasteventid);
//更新起始位置
query(emitter);
//开始生成位置信息
}
//根据last-event-id来更新起始位置
private
void
updateposition(string id) {
if
(id !=
null
) {
string[] pos = id.split(
","
);
if
(pos.length >
1
) {
int
xpos = -
1
, ypos = -
1
;
try
{
xpos = integer.parseint(pos[
0
],
10
);
ypos = integer.parseint(pos[
1
],
10
);
}
catch
(numberformatexception e) {
}
if
(isvalidmove(xpos, ypos)) {
x = xpos;
y = ypos;
}
}
}
}
private
void
query(emitter emitter)
throws
ioexception {
emitter.comment(
"start sending movement information."
);
while
(
true
) {
emitter.comment(
""
);
move();
//移动位置
string id = string.format(
"%s,%s"
, x, y);
emitter.id(id);
//根据位置生成事件标识符
emitter.data(id);
//发送位置信息数据
try
{
thread.sleep(
2000
);
}
catch
(interruptedexception e) {
logger.log(level.warning, \
"movement query thread interrupted. close the connection."
, e);
break
;
}
}
emitter.close();
//当循环终止时,关闭连接
}
@override
public
void
onclose() {
}
//获取下一个合法的移动位置
private
void
move() {
while
(
true
) {
int
[] move = getmove();
int
xnext = x move[
0
];
int
ynext = y move[
1
];
if
(isvalidmove(xnext, ynext)) {
x = xnext;
y = ynext;
break
;
}
}
}
//判断当前的移动位置是否合法
private
boolean
isvalidmove(
int
x,
int
y) {
return
x >=
0
&& x <= width && y >=
0
&& y <= height;
}
//随机生成下一个移动位置
private
int
[] getmove() {
int
[] xdir =
new
int
[] {-
1
,
0
,
1
,
0
};
int
[] ydir =
new
int
[] {
0
, -
1
,
0
,
1
};
int
dir = random.nextint(
4
);
return
new
int
[] {xdir[dir] * random.nextint(stepmax), \
ydir[dir] * random.nextint(stepmax)};
}
}