serialcommserver.java

来自「cqME :java framework for TCK test.」· Java 代码 · 共 203 行

JAVA
203
字号
/* * $Id$ *  * Copyright 1996-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER *  * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. *  * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). *  * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA *  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. *  */package com.sun.tck.j2me.services.commService.servers;import java.io.IOException;import java.io.DataInputStream;import java.io.DataOutputStream;import java.util.TooManyListenersException;import javax.comm.CommPortIdentifier;import javax.comm.SerialPort;import javax.comm.SerialPortEvent;import javax.comm.PortInUseException;import javax.comm.UnsupportedCommOperationException;import javax.comm.SerialPortEventListener;import javax.comm.NoSuchPortException;import com.sun.tck.j2me.communication.CommPacketHandler;import com.sun.tck.j2me.communication.CommunicationServer;import com.sun.tck.j2me.utils.ArgsDecoder;import com.sun.tck.j2me.utils.Closable;import com.sun.tck.j2me.utils.ClosableManager;public class SerialCommServer extends ArgsDecoder implements CommunicationServer {    private static final int DEFAULT_TIMEOUT = 2000;    private static final int DEFAULT_BAUD_RATE = 9600;        private CommPacketHandler packetHandler;    private int timeout;    private String commPort;    private CommPortIdentifier portId;    private SerialPort serialPort;    private ClosableManager resources = new ClosableManager();    private boolean verbose;    private int baudrate = DEFAULT_BAUD_RATE;    private int dataBits = SerialPort.DATABITS_8;    private int stopBits = SerialPort.STOPBITS_1;    private int parity = SerialPort.PARITY_NONE;    public SerialCommServer() {        timeout = DEFAULT_TIMEOUT;    }    public void init(String[] args) {        decodeArgs(args);        if (portId == null) {            throw new RuntimeException("SerialCommServer: commPort is null.");        }    }    public void start() throws IOException {        try {            serialPort = (SerialPort)portId.open("SerialCommServer", timeout);            serialPort.setSerialPortParams(baudrate, dataBits, stopBits, parity);            verboseln("Port opened: " + serialPort);        } catch (PortInUseException piuse) {            throw new IOException(piuse.toString());        } catch (UnsupportedCommOperationException ucoe) {            throw new IOException(ucoe.toString());        }        resources.add(new Closable() {            public void close() {                serialPort.close();            }        });        resources.add(new PortListener());    }    public void stop() throws IOException {        resources.close();    }    public String getServerAddress() throws IOException {        return commPort;    }    public void setPacketHandler(CommPacketHandler packetHandler) {        this.packetHandler = packetHandler;    }    protected int decodeArg(String[] args, int index)            throws IllegalArgumentException {        if (args[index].equals("-commPort") && index + 1 < args.length) {            this.commPort = args[index + 1];            try {                portId = CommPortIdentifier.getPortIdentifier(commPort);                if (portId.getPortType() != CommPortIdentifier.PORT_SERIAL) {                    throw new IllegalArgumentException("SerialCommServer: " +                            "commPort " + commPort + " is not serial");                }            } catch (NoSuchPortException nspe) {                throw new IllegalArgumentException("SerialCommServer: " +                        "commPort is invalid: " + commPort);            }            return 2;        } else if (args[index].equals("-baudRate") && index + 1 < args.length) {            try {                baudrate = Integer.parseInt(args[index + 1]);            } catch (NumberFormatException nfe) {                throw new IllegalArgumentException(nfe);            }            return 2;        } else if (args[index].equals("-verbose") && index + 1 < args.length) {            verbose = Boolean.parseBoolean(args[index + 1]);            return 2;        } else {            return super.decodeArg(args, index);        }    }    private class PortListener implements SerialPortEventListener, Closable {        DataInputStream is = null;        DataOutputStream os = null;        public PortListener() throws IOException {            try {                serialPort.addEventListener(this);            } catch (TooManyListenersException e) {}            is = new DataInputStream(serialPort.getInputStream());            os = new DataOutputStream(serialPort.getOutputStream());            serialPort.notifyOnDataAvailable(true);        }                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:                    verboseln("Data available event received");                    try {                        verboseln("Reading request...");                        String connID = is.readUTF(); // skip connection ID                        int length = is.readInt();                        verboseln("Should read " + length + " bytes");                        byte[] data = new byte[length];                        int read = 0;                        while (read < data.length) {                            read = read + is.read(data, read, data.length - read);                        }                        byte[] response = packetHandler.handlePacket(connID, data);                        os.writeInt(response.length);                        os.write(response);                        os.flush();                    } catch (IOException ioe) {                        ioe.printStackTrace();                    }                    break;                }        }        public void close() throws Exception {            serialPort.removeEventListener();            try {                if (is != null) is.close();            } catch (IOException ioe) {}            try {                if (os != null) os.close();            } catch (IOException ioe) {}        }    }    private void verboseln(String message) {        if (verbose) {            System.out.println(message);        }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?