打印机用Socket连接,端口号一般固定为9100。
private Socket socket;
/**
* 连接打印机
*/
public boolean connecte(String ipAddress) {
try {
if (socket != null && socket.isConnected()) {
socket.close();
}
SocketAddress ipe = new InetSocketAddress(ipAddress, 9100);
socket = new Socket();
//设置连接和超时时间
socket.connect(ipe, 2000);
return socket.isConnected();
} catch (IOException e) {
}
return false;
}
/**
* 断开打印机
* @return
*/
@Override
public boolean close() {
try {
if (socket != null && socket.isConnected()) {
socket.close();
}
socket = null;
return true;
} catch (IOException e) {
}
return false;
}
/**
* 打印操作
* @throws IOException
*/
public void print(byte[] bs) throws IOException {
if (bs.length > 0) {
socket.getOutputStream().write(bs);
socket.getOutputStream().flush();
}
}
/**
* 打印机是否连接
*/
public boolean isConnected() {
return (socket != null && socket.isConnected());
}
网友评论