返回> 网站首页 

java网络客户端与设备通讯 - SocketChannel

yoours2021-07-03 15:36:00 阅读 1916

简介一边听听音乐,一边写写文章。

一、来源

使用java实现原c++编写的设备sdk网络部分,其他部分如协议解析等直接改写成java代码。

二、java网络实现

package com.yoours.berryz2007.api;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SocketChannel;

class NetPort extends PortBase {

SocketChannel socketChannel = null;

public NetPort(){}

protected void finalize()

{

Close();

}

public boolean IsOpen() { return (socketChannel != null)&&socketChannel.isConnected(); }

public boolean Open(String ip, short usPort) {

try {

if (socketChannel != null)

return true;

socketChannel = SocketChannel.open();

if(socketChannel.connect(new InetSocketAddress(ip, usPort))) {

socketChannel.configureBlocking(false);

return true;

}

return false;

} catch (IOException e) {

return false;

}

}

public void Close()

{

if (socketChannel != null)

{

try {

socketChannel.close();

socketChannel=null;

}catch (IOException e){

}

}

}

public boolean ReadData(byte[] lpBuffer, int Len)

{

if (socketChannel == null) {

return false;

}

try {

ByteBuffer buffer = ByteBuffer.allocate(Len);

if(socketChannel.read(buffer)>0)

{

buffer.flip();//缓冲区读写模式变换

buffer.get(lpBuffer);

return true;

}

return false;

}catch (IOException e){

return  false;

}

}

public boolean WriteData(byte[] lpBuffer, int Len)

{

if (socketChannel == null) {

return false;

}

try {

socketChannel.write(ByteBuffer.wrap(lpBuffer, 0, Len));

}catch (IOException e)

{

return false;

}

return true;

}

}


微信小程序扫码登陆

文章评论

1916人参与,0条评论