80,349
社区成员
发帖
与我相关
我的任务
分享
public void readSocket()
{
Selector selector = TCPClient.instance().getSelector();
if (selector == null)
{
return;
}
try
{
// 如果没有数据过来,一直柱塞
while (selector.select() > 0)
{
for (SelectionKey sk : selector.selectedKeys())
{
// 如果该SelectionKey对应的Channel中有可读的数据
if (sk.isReadable())
{
// 使用NIO读取Channel中的数据
SocketChannel sc = (SocketChannel) sk.channel();
int size=1024*30;
ByteBuffer buffer = ByteBuffer.allocate(size);
//byte[] buffer=new byte[size];
try
{
sc.read(buffer);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
// continue;
}
buffer.flip();
String receivedString = "";
// 打印收到的数据
/*try
{*/
byte[] b=new byte[buffer.remaining()];
buffer.get(b, 0, b.length);
receivedString=ConvertUtils.byte2HexString(b);
// System.out.println(receivedString);
//receivedString=ConvertUtils.byte2HexString(buffer);
/*receivedString =Charset.forName("UTF-16")
.newDecoder().decode(buffer).toString();*/
CLog.e(tag, receivedString);
Intent i = new Intent(Const.BC);
i.putExtra("response", receivedString);
UIUtils.getContext().sendBroadcast(i);
/*} catch (CharacterCodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}*/
buffer.clear();
buffer = null;
try
{
// 为下一次读取作准备
sk.interestOps(SelectionKey.OP_READ);
// 删除正在处理的SelectionKey
selector.selectedKeys().remove(sk);
} catch (CancelledKeyException e)
{
e.printStackTrace();
}
}
}
}
// selector.close();
// TCPClient.instance().repareRead();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClosedSelectorException e2)
{
}
}
/**
* 发送数据
*
* @param bytes
* @throws IOException
*/
public void sendMsg(byte[] bytes) throws IOException
{
ByteBuffer writeBuffer = ByteBuffer.wrap(bytes);
System.out.println(ConvertUtils.byte2HexString(bytes));
if (socketChannel == null)
{
throw new IOException();
}
socketChannel.write(writeBuffer);
}
/**
* 服务器是否关闭,通过发送一个socket信息
*
* @return
*/
public boolean canConnectToServer()
{
try
{
if (socketChannel != null)
{ byte[] pinpon = { 0x00, 0x02, 0x00, 0x00, (byte) 0xD0, 0x00,
0x00 };
sendMsg(CRCUtils.initData(pinpon));
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}