⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serialchat.java

📁 人民邮电出版社的《J2ME手机开发入门》全部源代码
💻 JAVA
字号:
/*
 * SerialChat.java
 * 通过串口的聊天程序
 * Created on 2005-12-5, 11:00
 */

import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;


public class SerialChat extends MIDlet implements Runnable, CommandListener{
    private Display display;
    CommConnection ccCom = null;
    InputStream is = null;
    OutputStream os = null;
    boolean stopFlag = false;
    
    //=========================================================输入的窗体
    private TextBox tbInput;      //用于输入发送信息
    private Command cmdBack;      //返回
    private Command cmdSend;      //发送
    //==================================================================
    
    //=================================================校验串口设置的窗体
    private Form frmConfig;
    private ChoiceGroup cgSelectPort;   //选择端口
    private ChoiceGroup cgBaudrate;     //选择波特率
    private ChoiceGroup cgBitsperchar;  //选择字符位数
    private ChoiceGroup cgStopbits;      //选择停止位
    private ChoiceGroup cgParity;       //选择奇偶校验
    
    private Command cmdConfigOK;
    
    private String[] ports;        //串口列表
    //波特率设置
    private static final String[] BAUD_RATES = {"110",
            "300",
            "600",
            "1200",
            "2400",
            "4800",
            "9600",
            "14400",
            "19200",
            "34800",
            "56000",
            "57600",
            "115200",
            "128000",
            "256000"
    };
    //===================================================================
    
    //=================================================显示聊天信息的窗体
    Form frmChatMsg;        //显示聊天信息的窗体
    private Command cmdExit;        //退出按钮
    private Command cmdDispInput;   //打开输入界面
    private Command cmdDispConfig;  //打开串口校验窗体
    //===================================================================
    
    private Sender sender;
    
    public SerialChat() {
        display = Display.getDisplay(this);
        
        //=============================================初始化显示聊天信息的窗体
        this.frmChatMsg = new Form("聊天信息 - 未连接");
        this.frmChatMsg.setCommandListener(this);
        this.cmdExit = new Command("退出", Command.EXIT, 0);
        this.frmChatMsg.addCommand(this.cmdExit);
        
        //检测是否支持串口
        this.ports = this.availablePorts();
        if (this.ports == null) {
            this.frmChatMsg.setTitle("不支持串口");
            return;
        }
        
        this.cmdDispInput = new Command("输入", Command.ITEM, 1);
        this.frmChatMsg.addCommand(this.cmdDispInput);
        
        this.cmdDispConfig = new Command("设置", Command.ITEM, 2);
        this.frmChatMsg.addCommand(this.cmdDispConfig);
        //===================================================================
        
        //============================================初始化校验串口设置的窗体
        this.cmdConfigOK = new Command("确定", Command.ITEM, 1);
        
        this.frmConfig = new Form("配置串口");
        this.frmConfig.addCommand(this.cmdConfigOK);
        this.frmConfig.setCommandListener(this);
        
        this.cgSelectPort = new ChoiceGroup("请选择串口:",
                Choice.EXCLUSIVE, availablePorts(), null);
        this.cgBaudrate = new ChoiceGroup("请选择波特率:",
                Choice.POPUP, BAUD_RATES, null);
        this.cgBaudrate.setSelectedIndex(6, true);  //波特率 - 缺省9600
        this.cgBitsperchar = new ChoiceGroup("请选择位数:",
                Choice.EXCLUSIVE,
                new String[]{"8","7"
        }, null);
        this.cgStopbits = new ChoiceGroup("请选择停止位:",
                Choice.EXCLUSIVE,
                new String[]{"1",
                        "2"
        }, null);
        this.cgParity = new ChoiceGroup("请选择奇偶校验:",
                Choice.POPUP,
                new String[]{"none",
                        "odd",
                        "even"
        }, null);
        
        this.frmConfig.append(this.cgSelectPort);
        this.frmConfig.append(this.cgBaudrate);
        this.frmConfig.append(this.cgBitsperchar);
        this.frmConfig.append(this.cgStopbits);
        this.frmConfig.append(this.cgParity);
        //===================================================================
        
        //===============================================初始化输入信息的窗体
        this.tbInput = new TextBox("输入发送消息", "", 255, TextField.ANY);
        this.cmdBack = new Command("取消", Command.CANCEL, 0);
        this.tbInput.addCommand(this.cmdBack);
        this.cmdSend = new Command("发送", Command.OK, 0);
        this.tbInput.addCommand(this.cmdSend);
        this.tbInput.setCommandListener(this);
        //===================================================================
    }
    
    public void startApp() {
        if ((this.ccCom == null) && (this.ports != null)) {
            this.display.setCurrent(this.frmConfig);
        } else {
            this.display.setCurrent(this.frmChatMsg);
        }
    }
    
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
    }
    
    private String[] availablePorts() {
        Vector ports = getAvailableComPorts(1);
        if (ports==null) {
            ports = getAvailableComPorts(2);
        }
        
        String[] retVal = null;
        if (ports != null) {
            retVal = new String[ports.size()];
            for (int i = 0; i < retVal.length; i++) {
                retVal[i] = (String) ports.elementAt(i);
            }
        }
        return retVal;
    }
    
    private Vector getAvailableComPorts(int ver) {
        String propertyName=null;
        Vector ports = null;
        String portStr = null;
        
        if (ver == 1) {
            propertyName = "serialport.name";
        } else if (ver == 2) {
            propertyName = "microedition.commports";
        } else {
            return null;
        }
        
        try {
            portStr = System.getProperty(propertyName);
            System.out.println(portStr);
            if (portStr != null) {
                ports = new Vector();
                int comma = portStr.indexOf(',');
                while (comma > 0) {
                    //解析并显示端口列表
                    ports.addElement(portStr.substring(0, comma));
                    portStr = portStr.substring(comma+1);
                    comma = portStr.indexOf(',');
                }
                if (portStr != null) {
                    ports.addElement(portStr);
                }
            }
        } catch (Exception e) {
            System.out.println("当前手机不是MIDP " + String.valueOf(ver)+ ".0手机");
            return null;
        }
        return ports;
    }
    
    public void commandAction(Command c, Displayable s) {
        if (c == this.cmdExit) {
            //消息窗体 - 退出命令按钮
            this.stopFlag = true;
            try {
                this.wait(500);
                if (this.is != null) {
                    this.is.close();
                }
                if (this.os != null) {
                    this.os.close();
                }
                if (this.ccCom != null) {
                    this.ccCom.close();
                }
            }catch (Exception e) {
                System.out.println("Exception during exit: " + e.toString());
            } finally {
                this.is = null;
                this.os = null;
                this.ccCom = null;
            }
            destroyApp(true);
            notifyDestroyed();
        } else if (c == this.cmdDispConfig) {
            //消息窗体 - 显示串口配置窗体
            this.display.setCurrent(this.frmConfig);
        } else if (c == this.cmdConfigOK) {
            //串口配置窗体 - 确定按钮
            this.displayMsg();
        } else if (c == this.cmdDispInput) {
            this.display.setCurrent(this.tbInput);
        } else if (c == this.cmdBack) {
            //返回按钮
            this.display.setCurrent(this.frmChatMsg);
        } else if (c == this.cmdSend) {
            if (this.os != null) {
                sender = new Sender(this);
                String msg = this.tbInput.getString();
                sender.send(this.tbInput.getString());
                this.frmChatMsg.append("[发送]  " + msg);
                this.display.setCurrent(this.frmChatMsg);
            }
        }
    }
    
    private void displayMsg() {
        //开始接收数据的线程
        this.stopFlag = false;
        new Thread(this).start();
        this.display.setCurrent(this.frmChatMsg);
    }
    
    public synchronized void run() {
        try {
            int index = this.cgSelectPort.getSelectedIndex();
            String comp = this.cgSelectPort.getString(index);
            index = this.cgBaudrate.getSelectedIndex();
            String baudrate = this.cgBaudrate.getString(index);
            index = this.cgBitsperchar.getSelectedIndex();
            String bitsperchar = this.cgBitsperchar.getString(index);
            index = this.cgStopbits.getSelectedIndex();
            String stopbits = this.cgStopbits.getString(index);
            index = this.cgParity.getSelectedIndex();
            String parity = this.cgParity.getString(index);
            
            String conStr = "comm:" + comp  +
                    ";baudrate=" + baudrate +
                    ";bitsperchar=" + bitsperchar +
                    ";stopbits=" + stopbits +
                    ";parity=" + parity;
            System.out.println(conStr);
            this.ccCom = (CommConnection)Connector.open(conStr);
            System.out.println("打开端口正确");
            this.frmChatMsg.append("打开端口正确\n");
            int bt = this.ccCom.getBaudRate();
            this.frmChatMsg.setTitle("端口:"+ comp+"  波特率:" +
                    String.valueOf(bt));
        } catch (Exception e) {
            this.frmChatMsg.append("打开串口错误:" + e.toString());
            System.out.println("Exception open com port: " + e.toString());
        }
        
        try {
            int ch = 0;
            is = this.ccCom.openInputStream();
            os = this.ccCom.openOutputStream();
            while (!this.stopFlag) {
                int size = this.is.available();
                if (size>0) {
                    byte[] buf = new byte[size];
                    this.is.read(buf);
                    String str = new String(buf);
                    this.frmChatMsg.append("[接收]  " + str);
                    System.out.println("[接收]  " + str);
                }
                Thread.sleep(10);
            }
        } catch (Exception e) {
            this.frmChatMsg.append("接收数据时发生错误:" + e.toString());
            e.printStackTrace();
        }
    }
    
}

⌨️ 快捷键说明

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