jsp,java串口通信的问题

作者&投稿:咸袁 (若有异议请与网页底部的电邮联系)
求基于Java Web串口通信代码样例,能实现在JSP页面上显示服务器端串口的数据。~


synchronized 呀防止争用啦你既然在读 后面又打开,也就是再次打开 ,你做个判断也可以呀

可以,使用comm,jar

class SerialExample {

public static void main(String[] args) {
//TO DO: Add your JAVA codes here
long curTime = System.currentTimeMillis();
long serialtime = 8000;
boolean state = true;
SerialBean SB = new SerialBean(2);//设置端口号2
String Msg = "AD 01 0D";//发送命令
SB.Initialize(9600);//设置波率
SB.WritePort(Msg);//发送命令
/* for (int i = 5; i < 10; i++) {
System.out.println( SB.ReadPort(3));//设置读取个数
}
*/
String readdata = SB.ReadPort("0D",4000);//读取以OD结束的数据,4000ms没有数据就返回空
if (readdata.length() > 0) { //System.out.println(readdata.length());//如果有读到数据
System.out.println(readdata);//如果有读到数据
}
while (readdata.length() < 1 && state) {//如果没有读到数据
readdata = SB.ReadPort("0D",4000);
System.out.println(readdata);
if (System.currentTimeMillis() - curTime > serialtime) {
state = false;//设置读取错误超时
}
System.out.println("readdaa:" + state);
System.out.println(System.currentTimeMillis() - curTime);
}
if (!state) {
System.out.println("数据读取超时");
}
SB.ClosePort();//关闭连接
}
}

public class SerialBuffer {

Convents cv = new Convents();
private String Content = "";
private String CurrentMsg, TempContent;
private boolean available = false;
private int LengthNeeded = 1;
String str = "";
byte b;

/**
*
* This function returns a string with a certain length from the incoming
* messages.
*
* @param Length The length of the string to be returned.
*
*/
public synchronized String GetMsg(int Length) {
LengthNeeded = Length;
long timeout=2000;
long curtime=System.currentTimeMillis();
notifyAll();

if (LengthNeeded > Content.length()) {
available = false;
while (available == false) {
try {
if(System.currentTimeMillis()-curtime<timeout) wait();
} catch (InterruptedException e) {
}
}
}

CurrentMsg = Content.substring(0, LengthNeeded);
TempContent = Content.substring(LengthNeeded);
Content = TempContent;
LengthNeeded = 1;
notifyAll();
return CurrentMsg;
}

public synchronized String GetMsg(String endstring,long timeout) {
LengthNeeded =Content.indexOf(endstring);
notifyAll();
if (LengthNeeded < 0) {
available = false;
while (available == false) {
try {
wait(timeout);
available=true;
} catch (InterruptedException e) {
}
}
return "";
}
if (LengthNeeded > 0) {
CurrentMsg = Content.substring(0, LengthNeeded+endstring.length());
TempContent = Content.substring(LengthNeeded+endstring.length());
Content = TempContent;
}

LengthNeeded = -1;
notifyAll();
return CurrentMsg;

}

public synchronized void PutChar(int c) {
Content = Content.concat(cv.byteToHexString(c));
if (LengthNeeded < Content.length() && Content.length() > 0) {
available = true;
}
notifyAll();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package common.serial;

/**
*
* @author Jason
*/
import java.io.*;
import java.util.*;
import javax.comm.*;
import common.code.Convents;

public class SerialBean {
Convents cv=new Convents();
String PortName = "";
CommPortIdentifier portId = null;
SerialPort serialPort = null;
OutputStream out;
InputStream in;
SerialBuffer SB;
ReadSerial RT;
int rate=9600;
String endstring ="";
long timeout=2000;

public SerialBean(int PortID) {
PortName = "COM" + PortID;
}

public int Initialize(int rate) {

int InitSuccess = 1;
int InitFail = -1;

try {
portId = CommPortIdentifier.getPortIdentifier(PortName);
try {
serialPort = (SerialPort) portId.open("Serial_Communication", 2000);
} catch (PortInUseException e) {

return InitFail;
}

//Use InputStream in to read from the serial port, and OutputStream
//out to write to the serial port.

try {

in = serialPort.getInputStream();
out = serialPort.getOutputStream();
} catch (IOException e) {

return InitFail;
}

//Initialize the communication parameters to 9600, 8, 1, none.

try {

serialPort.setSerialPortParams(rate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

} catch (UnsupportedCommOperationException e) {

return InitFail;
}

} catch (NoSuchPortException e) {

return InitFail;
}
SB = new SerialBuffer();
RT = new ReadSerial(SB, in);
RT.start();
return InitSuccess;
}
public String ReadPort(int Length) {
String Msg;
Msg = SB.GetMsg(Length);
return Msg;
}
public String ReadPort(String endstring,long timeout) {
String Msg;
Msg = SB.GetMsg(endstring,timeout);
return Msg;
}
public void WritePort(String Msg) {
try {
out.write(cv.hexStringToByte(Msg));
} catch (IOException e) {
}
}
public void ClosePort() {
serialPort.close();
}
}

package common.serial;

import java.io.*;

public class ReadSerial extends Thread {
private SerialBuffer ComBuffer;
private InputStream ComPort;
char[] ch;

public ReadSerial(SerialBuffer SB, InputStream Port) {
ComBuffer = SB;
ComPort = Port;
}

@Override
public void run() {
int c;
try {
while (true) {
c=ComPort.read();
ComBuffer.PutChar(c);
}
} catch (IOException e) {
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package common.serial;
/**
*
* @author Administrator
*/
public class PortOpreate {
private String sendtxt="";
private String recivetxt="";
private int comid = 1;
private int comrate = 9600;
private int timeout = 4000;
private long waittime = 13000;
private String endtxt = "0D";
private boolean pstate=false;
private String massage="";
public void PortOpreate(boolean hasreturn) {
long curTime = System.currentTimeMillis();
long serialtime = getWaittime();
boolean state = true;
int t=0;
SerialBean SB = new SerialBean(getComid());//设置端口号2
t=SB.Initialize(getComrate());//设置波率
if(t>0){
SB.WritePort(getSendtxt());//发送命令
if (hasreturn) {
String readdata = SB.ReadPort(getEndtxt(), getTimeout());//读取以OD结束的数据,4000ms没有数据就返回空
if (readdata.length() > 0) { //System.out.println(readdata.length());//如果有读到数据
System.out.println(readdata);//如果有读到数据
}
while (readdata.length() < 1 && state) {//如果没有读到数据
readdata = SB.ReadPort(getEndtxt(), getTimeout());
System.out.println(readdata);
if (System.currentTimeMillis() - curTime > serialtime) {
state = false;//设置读取错误超时
}
System.out.println("readdaa:" + state);
System.out.println(System.currentTimeMillis() - curTime);
}
if (!state) {
System.out.println("数据读取超时");
setMassage("数据读取超时");
}
setRecivetxt(readdata);
setPstate(state);
}
SB.ClosePort();//关闭连接
}else{
System.out.println("端口号出现错误");
setMassage("端口号出现错误");
}
}

/**
* @return the sendtxt
*/
public String getSendtxt() {
return sendtxt;
}

/**
* @param sendtxt the sendtxt to set
*/
public void setSendtxt(String sendtxt) {
this.sendtxt = sendtxt;
}

/**
* @return the recivetxt
*/
public String getRecivetxt() {
return recivetxt;
}

/**
* @param recivetxt the recivetxt to set
*/
public void setRecivetxt(String recivetxt) {
this.recivetxt = recivetxt;
}

/**
* @return the comid
*/
public int getComid() {
return comid;
}

public void setComid(int comid) {
this.comid = comid;
}

public int getComrate() {
return comrate;
}

public void setComrate(int comrate) {
this.comrate = comrate;
}

public int getTimeout() {
return timeout;
}

public void setTimeout(int timeout) {
this.timeout = timeout;
}

public long getWaittime() {
return waittime;
}

public void setWaittime(long waittime) {
this.waittime = waittime;
}

public String getEndtxt() {
return endtxt;
}

public void setEndtxt(String endtxt) {
this.endtxt = endtxt;
}

public boolean isPstate() {
return pstate;
}

public void setPstate(boolean pstate) {
this.pstate = pstate;
}

public String getMassage() {
return massage;
}

public void setMassage(String massage) {
this.massage = massage;
}
}

package common.serial;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PortOperatorServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
long curTime = System.currentTimeMillis();
long serialtime = 8000;
boolean state = true;
String Msg = "AD 01 0D";//发送命令
SerialBean SB = new SerialBean(10);//设置端口号2
SB.Initialize(9600);//设置波率
SB.WritePort(Msg);//发送命令
/* for (int i = 5; i < 10; i++) {
System.out.println( SB.ReadPort(3));//设置读取个数
}
*/
String readdata = SB.ReadPort("0D",4000);//读取以OD结束的数据
if (readdata.length() > 0) { //System.out.println(readdata.length());//如果有读到数据
System.out.println(readdata);//如果有读到数据
}
while (readdata.length() < 1 && state) {//如果没有读到数据
readdata = SB.ReadPort("0D",4000);
System.out.println(readdata);
out.println(readdata);
if (System.currentTimeMillis() - curTime > serialtime) {
state = false;//设置读取错误超时
}
System.out.println("readdaa:" + state);
System.out.println(System.currentTimeMillis() - curTime);

}
if (!state) {
System.out.println("数据读取超时");
out.println("数据读取超时");
}
SB.ClosePort();//关闭连接
} finally {
out.close();
}
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

public String getServletInfo() {
return "Short description";
}

}

package common.code;

public final class Convents {

public final static char[] BToA = "0123456789abcdef".toCharArray();

/**
* 把16进制字符串转换成字节数组A1 01 0D
* @param hex
* @return
*/
public byte[] hexStringToByte(String hex) {
String str[] = hex.split(" ");
int len = str.length;
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
result[i] = (byte) (toByte(str[i].charAt(0)) * 16 + toByte(str[i].charAt(1)));
}
return result;
}

private static byte toByte(char c) {
byte b = (byte) ("0123456789ABCDEF".indexOf(c));
return b;
}

/**
* 把字节数组转换成16进制字符串
* @param bArray
* @return
*/
public String byteToHexString(int b){
String st="";
st=Integer.toHexString(b);
if (st.length() < 2) {
st="0"+Integer.toHexString(b).toUpperCase()+" ";
} else {
st=Integer.toHexString(b).toUpperCase()+" ";
}
return st;
}
public String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(bArray[i]).toUpperCase();

}
return sb.toString();
}
}

import gnu.io.SerialPort;
import java.util.HashMap;
public class CommTest {

public static void main(String[] args) {
HashMap <String, Comparable> params = new HashMap <String, Comparable>();
params.put(SerialReader.PARAMS_PORT, "COM8"); // 端口名称
params.put(SerialReader.PARAMS_RATE, 9600); // 波特率
params.put(SerialReader.PARAMS_TIMEOUT, 1000); // 设备超时时间 1秒
params.put(SerialReader.PARAMS_DELAY, 200); // 端口数据准备时间 1秒
params.put(SerialReader.PARAMS_DATABITS, SerialPort.DATABITS_8); // 数据位
params.put(SerialReader.PARAMS_STOPBITS, SerialPort.STOPBITS_1); // 停止位
params.put(SerialReader.PARAMS_PARITY, SerialPort.PARITY_NONE); // 无奇偶校验
SerialReader sr = new SerialReader(params);
CommDataObserver bob = new CommDataObserver("bob");
CommDataObserver joe = new CommDataObserver("joe");
sr.addObserver(joe);
sr.addObserver(bob);
}
}

---------------- 2 -----------------
package serial;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Observable;
import java.util.TooManyListenersException;
/**
* 串口数据读取类,用于windows的串口数据读取
*
*/
public class SerialReader extends Observable implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
int delayRead = 200;
int numBytes; // buffer中的实际数据字节数
private static byte[] readBuffer = new byte[4096]; // 4k的buffer空间,缓存串口读入的数据
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
HashMap serialParams;
// 端口读入数据事件触发后,等待n毫秒后再读取,以便让数据一次性读完
public static final String PARAMS_DELAY = "delay read"; // 延时等待端口数据准备的时间
public static final String PARAMS_TIMEOUT = "timeout"; // 超时时间
public static final String PARAMS_PORT = "port name"; // 端口名称
public static final String PARAMS_DATABITS = "data bits"; // 数据位
public static final String PARAMS_STOPBITS = "stop bits"; // 停止位
public static final String PARAMS_PARITY = "parity"; // 奇偶校验
public static final String PARAMS_RATE = "rate"; // 波特率
/**
* 初始化端口操作的参数.
*
*
* @see
*/
public SerialReader(HashMap params) {
serialParams = params;
init();
}
private void init() {
try {
// 参数初始化
int timeout = Integer.parseInt(serialParams.get(PARAMS_TIMEOUT).toString());
int rate = Integer.parseInt(serialParams.get(PARAMS_RATE).toString());
int dataBits = Integer.parseInt(serialParams.get(PARAMS_DATABITS).toString());
int stopBits = Integer.parseInt(serialParams.get(PARAMS_STOPBITS).toString());
int parity = Integer.parseInt(serialParams.get(PARAMS_PARITY).toString());
delayRead = Integer.parseInt(serialParams.get(PARAMS_DELAY).toString());
String port = serialParams.get(PARAMS_PORT).toString();
// 打开端口
portId = CommPortIdentifier.getPortIdentifier(port);
serialPort = (SerialPort) portId.open("SerialReader", timeout);
inputStream = serialPort.getInputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.setSerialPortParams(rate, dataBits, stopBits, parity);
} catch (PortInUseException e) {
System.out.println("端口已经被占用!");
e.printStackTrace();
} catch (TooManyListenersException e) {
System.out.println("端口监听者过多!");
e.printStackTrace();
} catch (UnsupportedCommOperationException e) {
System.out.println("端口操作命令不支持!");
e.printStackTrace();
} catch (NoSuchPortException e) {
System.out.println("端口不存在!");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Thread readThread = new Thread(this);
readThread.start();
}
/**
* Method declaration
*
*
* @see
*/
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
/**
* Method declaration
*
*
* @param event
*
* @see
*/
public void serialEvent(SerialPortEvent event) {
try {
// 等待1秒钟让串口把数据全部接收后在处理
Thread.sleep(delayRead);
System.out.print("serialEvent[" + event.getEventType() + "] ");
} catch (InterruptedException e) {
e.printStackTrace();
}
switch (event.getEventType()) {
case SerialPortEvent.BI: // 10
case SerialPortEvent.OE: // 7
case SerialPortEvent.FE: // 9
case SerialPortEvent.PE: // 8
case SerialPortEvent.CD: // 6
case SerialPortEvent.CTS: // 3
case SerialPortEvent.DSR: // 4
case SerialPortEvent.RI: // 5
case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2
break;
case SerialPortEvent.DATA_AVAILABLE: // 1
try {
// 多次读取,将所有数据读入
// while (inputStream.available() > 0) {
// numBytes = inputStream.read(readBuffer);
// }
numBytes = inputStream.read(readBuffer);
changeMessage(readBuffer, numBytes);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
// 通过observer pattern将收到的数据发送给observer
// 将buffer中的空字节删除后再发送更新消息,通知观察者
public void changeMessage(byte[] message, int length) {
setChanged();
byte[] temp = new byte[length];
System.arraycopy(message, 0, temp, 0, length);
// System.out.println("msg[" + numBytes + "]: [" + new String(temp) + "]");
notifyObservers(temp);
}
static void listPorts() {
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements()) {
CommPortIdentifier portIdentifier = (CommPortIdentifier) portEnum.nextElement();
System.out.println(portIdentifier.getName() + " - "
+ getPortTypeName(portIdentifier.getPortType()));
}
}
static String getPortTypeName(int portType) {
switch (portType) {
case CommPortIdentifier.PORT_I2C:
return "I2C";
case CommPortIdentifier.PORT_PARALLEL:
return "Parallel";
case CommPortIdentifier.PORT_RAW:
return "Raw";
case CommPortIdentifier.PORT_RS485:
return "RS485";
case CommPortIdentifier.PORT_SERIAL:
return "Serial";
default:
return "unknown type";
}
}
/**
* @return A HashSet containing the CommPortIdentifier for all serial ports that are not
* currently being used.
*/
public static HashSet <CommPortIdentifier> getAvailableSerialPorts() {
HashSet <CommPortIdentifier> h = new HashSet <CommPortIdentifier>();
Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
while (thePorts.hasMoreElements()) {
CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement();
switch (com.getPortType()) {
case CommPortIdentifier.PORT_SERIAL:
try {
CommPort thePort = com.open("CommUtil", 50);
thePort.close();
h.add(com);
} catch (PortInUseException e) {
System.out.println("Port, " + com.getName() + ", is in use.");
} catch (Exception e) {
System.out.println("Failed to open port " + com.getName() + e);
}
}
}
return h;
}
}

---------- 3 -----------------
package serial;
import java.util.Observable;
import java.util.Observer;
class CommDataObserver implements Observer {
String name;
public CommDataObserver(String name) {
this.name = name;
}
public void update(Observable o, Object arg) {
System.out.println("[" + name + "] GetMessage:\n [" + new String((byte[]) arg) + "]");
}
}

读取串口需要1.COMM.JAR;2.javax.comm.properties;3.win32com.dll;三个文件

package com.test2;

import java.io.*;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;

public class CommUtil implements SerialPortEventListener {

InputStream inputStream; // 从串口来的输入流
OutputStream outputStream;// 向串口输出的流
SerialPort serialPort; // 串口的引用
CommPortIdentifier portId;

public CommUtil(Enumeration portList, String name) {
while (portList.hasMoreElements()) {
CommPortIdentifier temp = (CommPortIdentifier) portList.nextElement();
if (temp.getPortType() == CommPortIdentifier.PORT_SERIAL) {// 判断如果端口类型是串口
if (temp.getName().equals(name)) { // 判断如果端口已经启动就连接
portId = temp;
}
}
}
try {
serialPort = (SerialPort) portId.open("My"+name, 2000);
} catch (PortInUseException e) {

}
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
}
try {
serialPort.addEventListener(this); // 给当前串口天加一个监听器
} catch (TooManyListenersException e) {
}
serialPort.notifyOnDataAvailable(true); // 当有数据时通知
try {
serialPort.setSerialPortParams(2400, SerialPort.DATABITS_8, // 设置串口读写参数
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
}
}

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:// 当有可用数据时读取数据,并且给串口返回数据
byte[] readBuffer = new byte[20];

try {
while (inputStream.available() > 0) {
//System.out.println(inputStream.available()); //字符串长度
int numBytes = inputStream.read(readBuffer);
//System.out.println(numBytes);
}
System.out.println(new String(readBuffer).trim());
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
public void send(String content){
try {
outputStream.write(content.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}

public void read(){
try {
inputStream.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void ClosePort() {
if (serialPort != null) {
serialPort.close();
}
}

}

测试

package com.kmtweight.dao;

import java.util.Enumeration;

import javax.comm.CommPortIdentifier;

import com.kmtweight.com.CommUtil;

public class test {

public static void main(String[] args) throws InterruptedException {
Enumeration portList = CommPortIdentifier.getPortIdentifiers(); //得到当前连接上的端口
CommUtil comm3 = new CommUtil(portList,"COM1");
int i = 0;
//写数据
// while(i<5)
// {
// Thread.sleep(3000);
// //comm3.send("hello");
// comm3.read();
// i++;
// }
//读数据
while(true){
comm3.read();
}
// comm3.ClosePort();
}

}

希望是你需要的,我也刚找到的。


netapp 如何开启远程串口 SP
首先在你安装完成后,需要对系统做setup,配置基本的后面,会有相关SP的配置。需要你分配相关的 IP地址,网关、DNS等等。开启后,将SP端口接入到交换机,即可通过SP登陆。另外,如果对于SP不熟悉,可以把console口也接入到服务器。目前来看,SP端口的使用功能比以前的BMC要强大。一些BUG引起的命令好,就需...

白菜价,sp和ssp什么意思?
SP意味着更高级的Offer。SSP(SynchronousSerialPort)是一个同步串行端口控制器,可控制SPI.4线SSI或Microwire总线的操作。在一个总线上可以有多个主机和从机,但是在一次数据传输过程中,总线上进行数据通信的只能有一个主机和一个从机。数据传输原则上是全双工的,4~16位帧的数据由主机发送到从机或由从...

et200sp串口通信模块发送接收指示灯慢
缓冲区太小。缓冲区太小导致溢出,你线程去取串口数据时其实已经可能丢失了。或者软件设计问题,特别是你的串口控件的Inbuffersize属性,不能设置过大,要大小适合。也可能是你的程序中是否有延迟代码。模块通过接口向外发送数据。

sp3232与max3232都用于串口通信,它们之间有什么区别?
sp3232与max3232的5种区别 ⑴是一种RS-232标准的变种,只是码制、波特率等等和RS-232定义都是一样的,只有一点不一样,就是高低电平的定义。⑵单片机高电平一般是VCC,而低电平一般是GND。而RS-232标准的高电平是负逻辑,而低电平是正逻辑。⑶电脑的COM口就是标准RS-232接口,它的高电平定义为-12V...

windows 串口常用的几个函数
sp.Read(readBuffer, 0, readBuffer.Length); \/\/赋值 receiveStr=readBuffer;\/\/当然你可以通过转换将byte[]转换为字符串。 }\/\/你要求的按钮事件可以这么写 private void button1_Click(object sender,

SP的英文缩写
××SP1是××(指软件,系统)的第一个补丁包。如:Windows 7 SP1即为Windows 7的第一个补丁包,A8 3.10 SP1即为A8 3.10的第一个补丁包。3.SP = Stuff Pack物品包,填充包。如:模拟人生3 的SP02 Fast Lane Stuff,《桌游志》杂志附送的三国杀补充包武将。4.SP = Sex Pistols性手枪,...

C# SerialPort sp 获取端口缓冲区中的所有内容原理
串口收到数据后会自动保存到串口缓冲区中,然后在适当的时机发出DataReceived事件通知程序。程序在DataReceived事件中,先查询BytesToRead属性获取缓冲区的字节数量,然后调用Read方法去读取出所有的字节。

c#如何实现串口通信读取数据
e){byte[] buffer = new byte[sp.BytesToRead];sp.Read(buffer, 0, buffer.Length);string str = EncodingType.GetString(buffer);if (OnComReceiveDataHandler != null){OnComReceiveDataHandler(str);}}#endregion} }View Code 三、编写Winform串口通信工具界面 界面预览 ...

...mysp,在主窗口LOAD的时候初始化,并打开了串口。
= serialPort1;form2.ShowDialog();} } \/\/form2里的关键代码 public SerialPort serialport { get; set; } \/\/点击form2中的按钮后关闭串口对象 private void button1_Click(object sender, EventArgs e){ serialport.Close();this.DialogResult = System.Windows.Forms.DialogResult.OK;} ...

C#窗体应用,如何在串口设置窗口关闭后再次打开还是之前设置的界面呢...
public static SerialPort sp=new SerialPort();之后在form2中就可以直接使用form1.sp来控制串口,至于保存设置,方法很多,可以用注册表或者ini(C#中对ini的读写你自己查一下很容易找到),当在form2点打开串口的时候,先将上面的这些设置保存到ini里,然后再打开,同样在form2的load里,先读取这些...

门头沟区13795939124: java串口通信出现如下错误.(是不是配置有问题啊).求高手相助 -
杨颖复合: 您好,导入的包被限制,解决方式 选中项目--右键--进入Properties(属性)视图 选中Java Build Path--点击Libraries--展开JRE System Library[JavaSE-X],选中Access rules这一项(如果没有,那就是JDK安装和配置的问题).Edit--点击Add--在Rule Pattern(规则式样)编辑你允许导入的类库 看看是否能解决,希望帮到你!

门头沟区13795939124: 在java的web程序中怎么使用串口通讯? -
杨颖复合: 方法如下:1. 新建eclipse工程,添加comm.jar或者RXTXcomm.jar包.因为javacomm20-win32.zip包里有样例SimpleRead.java,可以通过这个例子测试串口是否正确.2. 接收数据正确后,根据传送接收双方的协议,采用CRC循环校验,根据传...

门头沟区13795939124: java 串口通信问题 无法向串口发送数据 也不报错 -
杨颖复合: 把串口的RX、和TX,连接起来,再做发送和接收的测试,就知道有没有发送成功了.

门头沟区13795939124: 你好 我想问你一下有关javaWEB串口读取数据的问题 -
杨颖复合: 最好远程调试一下,看看点击按钮之后,你有没有成功接受到指令,并开始执行串口读取方法,如果还是执行了,那很可能是你写的方法哪里错了,定位,解决.这个应该不会存在什么死循环的问题.

门头沟区13795939124: java 串口通信modbus异常,那个问题,请问您怎么解决的? -
杨颖复合: 从提示信息来看 主要两点 第一点 串口通讯包 dll 和jar文件版本不匹配 第二点 没有new一个modbus对象

门头沟区13795939124: java串口通信数据丢失,怎么解决 -
杨颖复合: 解决办法:1、将两台PC间波特率设置为一样的大小.2、采取进距离传输,随着距离的增加,信息衰减率也便增加.3、尽量采用低波特率传输,这样误码率会大大减少.4、加入数据校验功能,在接收数据一方实现“奇偶校验法”等方法验证数据传输的完整性.

门头沟区13795939124: 如何解决字符串从jsp传到java中乱码情况? -
杨颖复合: 方法一:设置 request 和 response 的编码 [ 页面编码必须为 u8 ] request.setCharacterEncoding("UTF-8");//传值编码 response.setContentType("text/html;charset=UTF-8");//设置传输编码 方法二:String str1=传来的数据.String ss=new String(str1.getBytes("ISO-8859-1"),"utf-8"); //转码UTF8

门头沟区13795939124: 请教一个关于java与串口通信的问题 -
杨颖复合: 电子称有动态链接库,你使用JNI实现里面的接口就行了.java直接操作是没办法发送的.

门头沟区13795939124: java串口通讯 为什么我先用OutputStream流向串口发送数据成功后,用InputStream流读不到数据 -
杨颖复合: 1、首先确保你发送的数据是正确的,串口接收到这个数据后他能识别,并返回你想要的数据,如果你发送的命令本身不要求返回数据,inputstream是读取不到数据的.2、其次,要确保发送数据的格式正确,比如一段16进制数据,你定义为String="01230545"类型,然后发送的时候out.write(str.getBytes());这样发送的数据是不对的,应该定义一个byte型的数组,然后发送这个数组3、以上你都确保没问题了,你可以用循环去读取数据,当读到的内容大于0时停止读取.用循环读取你要确保你已经设置读取的超时时间了,不然程序有可能阻塞.

门头沟区13795939124: 用java实现串口通信,怎么能区分同时发送的两条或多条数据? -
杨颖复合: 串口,就是一个入口.数据来源不同,只有在数据中分辨.或者,通过关闭、再打开来区别

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网