How:Java实现RS232串口通信

先来看一幅图:


说明:1.图中只是指出了其核心部分,要实现自己特定的软件功能可在此基础上扩展

            2.理解包中各个类:

              An application first uses methods in CommPortIdentifier to negotiate with the driver to discover which communication ports are available and then select a port for opening. It then uses methods in other classes like CommPortParallelPort and SerialPort to communicate through the port.

实例:

    1.获取所有可用串口并添加到列表框(其中portList为列表框)

Enumeration comIdentifiersEn=CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId=null;
while(comIdentifiersEn.hasMoreElements())
{
	portId=(CommPortIdentifier) comIdentifiersEn.nextElement();
	if(portId.getPortType()==CommPortIdentifier.PORT_SERIAL)
	portList.addItem(portId.getName());
}

    2.打开端口(含各种初始化工作)

   		try {
			 sPort=(SerialPort) com.open(ownerName, 60);
		} catch (PortInUseException e) {
			// TODO Auto-generated catch block
			System.out.println("端口已被占用!");
			e.printStackTrace();
		}
		//sPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
		setPortParameters(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
		try {
			inputStream=sPort.getInputStream();
			outputStream=sPort.getOutputStream();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			sPort.addEventListener(this);
		} catch (TooManyListenersException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sPort.notifyOnDataAvailable(true);
		try {
			sPort.enableReceiveTimeout(2000);
		} catch (UnsupportedCommOperationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    3.写数据

outputStream.write((int)stringToWrite.charAt(i));
  4.读数据
switch(serialEvent.getEventType())
		{
		case SerialPortEvent.DATA_AVAILABLE:
			char tmpReceivedChar;
			try {
				//System.out.print((char)inputStream.read());
				//messageAreaIn.append(""+(char)inputStream.read());
				while((tmpReceivedChar=(char)inputStream.read())!=(char)-1) //保证将数据读完
				{
					while(tmpReceivedChar!='\n')
					{
						tmpReceivedString+=tmpReceivedChar;
						tmpReceivedChar=(char) inputStream.read();
					}
					if(!isFile)
					{
						if(tmpReceivedString.equals(START_FILE))
						{
							isFile=true;
							isFileName=true;
							tmpReceivedString="";
						}
						else if(tmpReceivedString.equals(END_FILE))
						{
							//messageAreaIn.append("");
							tmpReceivedString="";
						}
						else
						{
							messageAreaIn.append(dateManager.getFormattedTime()+" receive:\n    "+tmpReceivedString+"\n");
							messageAreaIn.setCaretPosition(messageAreaIn.getText().length());//使文本自动移到最后
							tmpReceivedString="";
						}
					}
					else
					{
						if(isFileName)  //若是文件那么将接下来的第一个字符串作为文件名创建文件类,并连接到PrintWriter
						{
							File folderCreater=new File("./received");
							folderCreater.mkdir();
							File fileReceived=new File("./received/"+tmpReceivedString);
							tmpReceivedString="";
							//判断该文件名是否已经存在??
							
							outputStreamToFile=new PrintWriter(new FileOutputStream(fileReceived));
							isFileName=false;
							isLength=true;
							System.out.println("alreay creat the file !");
						}
						else if(isLength)
						{
							lengthOfReceivedFile=Integer.parseInt(tmpReceivedString);
							tmpReceivedString="";
							if(!isReceivingBarStart)
							{
								System.out.println("before receivingBar start");
								ReceivingBarThread receivingBar=new ReceivingBarThread();
								receivingBar.start();
								System.out.println("receivingBar started !");
								isReceivingBarStart=true;
							}
							System.out.println("Got length is "+lengthOfReceivedFile);
							isLength=false;
							isFirstLine=true;
						}
						else if(tmpReceivedString.equals(END_FILE))
						{
							outputStreamToFile.close();
							isFile=false;
							tmpReceivedString="";
							alreadyReceivedLength=lengthOfReceivedFile;
							System.out.println("File sending is over !");
						}
						else
						{
							if(isFirstLine)
							{
								outputStreamToFile.print(tmpReceivedString);
								alreadyReceivedLength+=tmpReceivedString.length()+2;
								isFirstLine=false;
							}
							else
							{
								outputStreamToFile.println();
								outputStreamToFile.print(tmpReceivedString);
								alreadyReceivedLength+=tmpReceivedString.length()+2;
								System.out.println("alreadyReceivedLength is "+alreadyReceivedLength);
							}
							tmpReceivedString="";
							System.out.println("receiving the file");
						}
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}








  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值