public
class
SocketTest
extends
Thread{
private
int
_timerCount =
0
;
private
boolean
_connect =
false
;
private
TimerTask _reconnectTimer;
public
final
static
int
TECH_INFO =
0X65
;
private
static
final
int
BUFFER_LEN =
1024
;
private
static
final
int
COMMAND_LEN =
1
;
public
final
static
int
TECH_STAND =
0
;
public
final
static
int
TECH_TABLE =
1
;
public
final
static
int
TECH_PORTABLE =
2
;
public
ServerSocket serverSocket;
public
Socket socket =
null
;
private
int
port =
9123
;
public
void
run()
{
try
{
Log.d(
"msg"
,
"socket thread start"
);
serverSocket =
new
ServerSocket(port);
while
(
true
) {
socket = serverSocket.accept();
if
(_connect ==
false
)
NotifyConnect();
try
{
BufferedInputStream bis =
new
BufferedInputStream(socket.getInputStream());
byte
[] buffer =
new
byte
[BUFFER_LEN];
while
(socket.isConnected()) {
int
bytesRead = bis.read(buffer,
0
, BUFFER_LEN);
if
(bytesRead >=
0
) {
byte
command = buffer[
0
];
byte
[] content =
null
;
int
length =
0
;
if
(bytesRead > COMMAND_LEN) {
content =
new
byte
[bytesRead - COMMAND_LEN];
length = content.length;
System.arraycopy(buffer, COMMAND_LEN, content,
0
, length);
}
Log.d(
"msg"
,
"commnad"
+command +
"content"
+ content +
"length"
+ length);
}
else
{
throw
new
Exception(
"Read is -1"
);
}
}
}
catch
(Exception e) {
NotifyDisconnect();
}
}
}
catch
(Exception e) {
}
}
public
void
NotifyConnect()
{
_connect =
true
;
ReconnectTimerStart();
}
public
void
ReconnectTimerStart()
{
final
byte
[] a =
new
byte
[
1
];
a[
0
] = (
byte
) TECH_PORTABLE;
final
byte
[] b =
new
byte
[
1
];
b[
0
] = (
byte
) TECH_TABLE;
final
byte
[] c =
new
byte
[
1
];
c[
0
] = (
byte
) TECH_PORTABLE;
_timerCount =
0
;
_reconnectTimer =
new
TimerTask()
{
@Override
public
void
run() {
switch
(_timerCount)
{
case
0
:
sendCommandData(TECH_INFO, a);
break
;
case
5
:
sendCommandData(TECH_INFO, b);
break
;
case
10
:
sendCommandData(TECH_INFO, c);
break
;
}
_timerCount++;
if
(_timerCount >
10
)
{
_timerCount=
0
;
}
}
};
Timer timer =
new
Timer();
timer.schedule(_reconnectTimer,
2000
,
1000
);
}
public
void
NotifyDisconnect()
{
}
public
byte
[] sendCommandData(
int
command,
byte
[] data) {
byte
[] packet =
new
byte
[data.length + COMMAND_LEN];
packet[
0
] = (
byte
)command;
System.arraycopy(data,
0
, packet,
1
, data.length);
sendPacket(packet);
return
packet;
}
public
void
sendPacket(
byte
[] packet) {
try
{
Log.d(
"msg"
,
"socket send packet"
);
if
(socket ==
null
|| socket.isConnected() ==
false
)
return
;
synchronized
(
this
) {
BufferedOutputStream bos =
new
BufferedOutputStream(socket.getOutputStream());
Log.d(
"msg"
,
"socket send packet1"
);
bos.write(packet,
0
, packet.length);
Log.d(
"msg"
,
"socket send packet2"
);
bos.flush();
Log.d(
"msg"
,
"socket send packet3"
);
}
}
catch
(Exception e) {
for
(StackTraceElement element : e.getStackTrace()) {
}
NotifyDisconnect();
}
}
}