java comm如何监听串口断开,或者有什么接口可以判断是否连接状态

java comm如何监听串口断开,或者有什么接口可以判断是否连接状态,第1张

public void serialEvent(SerialPortEvent event) {

switch (event.getEventType()) {

case SerialPortEvent.BI:

case SerialPortEvent.OE:

case SerialPortEvent.FE:

case SerialPortEvent.PE:

case SerialPortEvent.CD:

case SerialPortEvent.CTS:

case SerialPortEvent.DSR:

case SerialPortEvent.RI:

case SerialPortEvent.OUTPUT_BUFFER_EMPTY:

break

case SerialPortEvent.DATA_AVAILABLE:

//commread()

break

default:

break

}

}这就是串口的监听事件 通过eventtype判断

比如我要监听1234这个端口,代码如下:

String ip = "127.0.0.1"

int port = 1234

try {

Socket socket = new Socket(ip, port)

socket.setSoTimeout(5539900)

java.io.OutputStream out = socket.getOutputStream()

byte[] date = "hello world".getBytes()

out.write(data)

out.flush()

byte[] buffer = new byte[1024]

int len = -1

java.io.FileOutputStream fout = new java.io.FileOutputStream(

"d:/response.txt")

java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream()

java.io.InputStream in = socket.getInputStream()

while ((len = in.read(buffer, 0, buffer.length)) >0) {

bout.write(buffer, 0, len)

}

in.close()

bout.flush()

bout.close()

byte[] rdata = bout.toByteArray()

System.out.println(new String(rdata))

fout.write(rdata)

fout.flush()

fout.close()

socket.close()

} catch (UnknownHostException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

}

服务器端的

ServerSocket ss = new ServerSocket(1234)

Socket socket=null

BufferedReader in

PrintWriter out

while (true) {

socket = ss.accept()

in = new BufferedReader(new InputStreamReader(socket.getInputStream()))

out = new PrintWriter(socket.getOutputStream(),true)

String line = in.readLine()

out.println("you input is :" + line)

out.close()

in.close()

socket.close()

}

这应该不好做。毕竟串口不像以太网,以太网是广播的,自然可以很容易实现第三方监控。

串口的话,你需要干预进去到硬件驱动层面想办法

还有,从硬件上想办法,如用个串口转以太网转化器,之后在网络上侦听


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/8116155.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存