| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 506 人关注过本帖
标题:java 基于串口的聊天工具读写不了串口中的数据(类似于QQ)(求助)
只看楼主 加入收藏
妖孽玉流星
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2011-5-1
收藏
 问题点数:0 回复次数:0 
java 基于串口的聊天工具读写不了串口中的数据(类似于QQ)(求助)
package load;
import *;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.JDialog;
import
import Dlg.DlgAbout;
@SuppressWarnings("serial")
public class jiemian extends JFrame implements ActionListener,Runnable
{ //定义qq界面所需的组件
    private ComAccess ca = new ComAccess(3);
    static JPanel p1 = new JPanel(), p2 = new JPanel();
    TextArea output = new TextArea("", 20, 18, TextArea.SCROLLBARS_BOTH),
    input = new TextArea("", 20, 18, TextArea.SCROLLBARS_VERTICAL_ONLY);
    JButton b_biaoqing = new JButton("表情");
    JButton b_zhiti = new JButton("字体");
    JButton b_zhitiys = new JButton("字体颜色");
    JButton b_jilu = new JButton("清空消息");
    JButton b_fasong = new JButton("发送");
    JLabel youbian = new JLabel();
   
    Color ys = new Color(157, 242, 173);
    caidan cd = new caidan(); //获得菜单对象
    Thread thread2=new Thread(this);
   
    // 显示“关于”对话框
    public void showAbout(){
        DlgAbout ad = new DlgAbout(this);
        ad.show();
    }
   
    public jiemian()
    { //布局聊天界面
        super("zigbee聊天工具(FFD端)");
        ca.Initialize();//初始化串口以及打开串口

        thread2.start();
        
        setMenuBar(cd);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        b_jilu.addActionListener(this);
        b_fasong.addActionListener(this);
        b_biaoqing.addActionListener(this);
        b_zhiti.addActionListener(this);
        b_zhitiys.addActionListener(this);

        Container cc = getContentPane();
        setBounds(150, 150, 600, 510);
        cc.setLayout(new BorderLayout());
        output.setBackground(Color.white);
        output.setForeground(Color.blue);
        output.setBounds(4, 0, 420, 250);
        output.setFont(new Font("楷体", Font.PLAIN, 14));
        output.setEditable(false);

        p1.setLayout(null);
        p1.setBackground(new Color(220, 220, 220));
        p1.add(output);
        b_biaoqing.setBounds(4, 254, 60, 30);
        p1.add(b_biaoqing);
        b_zhiti.setBounds(65, 254, 60, 30);
        p1.add(b_zhiti);
        b_zhitiys.setBounds(126, 254, 90, 30);
        p1.add(b_zhitiys);
        input.setFont(new Font("楷体", Font.PLAIN, 14));
        input.setBackground(Color.white);
        input.setForeground(Color.blue);
        input.setBounds(4, 290, 420, 125);
        p1.add(input);
        b_jilu.setBounds(4, 420, 100, 30);
        p1.add(b_jilu);
        b_fasong.setBounds(330, 420, 60, 30);
        p1.add(b_fasong);
        p1.setBackground(ys);
        cc.add(p1, "Center");
        
        youbian.setIcon(new ImageIcon("photo/11.jpg"));
        p2.add(youbian);
        p2.setBackground(ys);
        p2.setLayout(new GridLayout(1, 2, 1, 10));
        cc.add(p2, "East");
        setVisible(true);
            
    }

    public jiemian(jiemian jm) {}

    //执行按钮动作的方法
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == b_fasong)
        {
            String ss = input.getText();
            if (ss.equals("")){ jiemian test = new jiemian(this); }
            else { sendData1(); }
        }
        else if (e.getSource() == b_zhiti)
        {
            ziti zt = new ziti(this);
            input.setFont(zt.f);
            output.setFont(zt.f);
        }
        else if (e.getSource() == b_zhitiys)
        {
            Color newcolor = JColorChooser.showDialog(this, "调色板",
            input.getForeground());
            input.setForeground(newcolor);
            output.setForeground(newcolor);
        }
        else if (e.getSource() == b_jilu) { output.setText(""); }
    }
//    向串口发送数据,参见HMS中函数msgSent的注释
//发送及接受数据的方法
    void sendData1()
    {
        int len;
        try
        {
            Calendar rightNow = Calendar.getInstance(); //获取当前系统日期和时间
            int hour = rightNow.get(Calendar.HOUR_OF_DAY); //获取当前时间的整点数
            int year = rightNow.get(Calendar.YEAR);
            int month = rightNow.get(Calendar.MONTH) + 1;
            int day = rightNow.get(Calendar.DATE);
            int minute = rightNow.get(Calendar.MINUTE);
            int second = rightNow.get(Calendar.SECOND);

            String msg = input.getText();
            if (msg.equals("")) { return; }
            input.setText("");
            //String ad = IPAdd.getText();
            InetAddress tea = InetAddress.getLocalHost();
            String asd = tea.getHostAddress(); //发送方的IP地址
            output.append(cd.nicheng1 + "(" + asd + ") " + year
            + "-" + month + "-"
            + day + " "
            + hour + ":"
            + minute + ":"
            + second + "\n" + " " + msg
            + "\n");
            msg = cd.nicheng2 + "(" + asd + ") " + year
            + "-" + month + "-"
            + day + " "
            + hour + ":"
            + minute + ":"
            + second + "\n" + " " + msg + "\n";
            
            len=msg.length();
            ca.WritePort(msg.substring(0,len));
            // 延时,防止发送失败
            try {Thread.sleep(2000);}
            catch (InterruptedException e) {e.printStackTrace();}
        }
        catch (Exception e) { }
    }
   
    //等待接受数据的方法
    public void run()
    {
        try
        {
            while(true)
            {//每隔一秒读取串口数据
                try {Thread.sleep(1000);}
                catch (InterruptedException e) {e.printStackTrace();}
                for (int i = 5; i <= 10; i++)
                {
                    String s=ca.ReadPort(i);
                    output.append(s+"\n");   
                }   
            }
        }
        catch (Exception e) { }
    此次界面代码是不重要的代码省略了.............................
}

为什么读写不了串口
串口读写方法:
ComAccess.java代码
package CommAccess;

import *;
import *;

public class ComAccess
{
    static String PortName;
    CommPortIdentifier portId;
    SerialPort serialPort;
    static OutputStream out;
    static InputStream  in;
    ComBuffer CB;
    ReadCom   RT;
    boolean   bCanExit = true;
    //打开由PortID指定的端口,即与GSM模块相连的串口
    public ComAccess(int PortID)
    {
        PortName = "COM" + PortID;
    }
    //初始化串口
    public int Initialize()
    {
        int InitSuccess = 1;
        int InitFail    = -1;
        try
        {
            portId = CommPortIdentifier.getPortIdentifier(PortName);
            try
            {
                serialPort = (SerialPort)portId.open("Serial_Communication", 2000);
            }
            catch (PortInUseException e)
            {
                System.out.println("try to open serialPort error:portId.open()");
                return InitFail;
            }
            try
            {
                //System.out.println("try to stream");   
                in  = serialPort.getInputStream();
                out = serialPort.getOutputStream();
            }
            catch (IOException e)
            {
                System.out.println("try to ini stream error:getInputStream()");
                return InitFail;
            }        
            try
            {               
                serialPort.setSerialPortParams(19200,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
            }
            catch (UnsupportedCommOperationException e)
            {
                System.out.println("try to config port error:setSerialPortParams()");
                return InitFail;
            }            
        }
        catch (NoSuchPortException e)
        {
            return InitFail;
        }   
        CB = new ComBuffer();      //创建一个读串口缓充区   
        RT = new ReadCom(CB,in);   //创建一个读线程
        RT.start();                //线程开始运行  
        return InitSuccess;
    }   
    public String ReadPort(int Length)
    {
        String Msg;
        Msg =CB.GetMsg(Length);
        return Msg;
    }
    public void WritePort(String Msg)
    {
        int i;
        try
        {
            bCanExit = false;   //发送进行中是不允许退出的
            for (i = 0; i < Msg.length() ; i++)
            {
                out.write(Msg.charAt(i));
                try {Thread.sleep(100);}
                catch (InterruptedException e) {e.printStackTrace();}
            }      
            bCanExit = true;
        }
        catch (IOException e){}
    }
    public void ClosePort()
    {
        // 等待,直到可以退出为止
        while(!bCanExit)      
        {
            try {Thread.sleep(100);}
            catch (InterruptedException e) {e.printStackTrace();}
        }   
        RT.interrupt();
        RT.stop();
        serialPort.close();
    }   
}
ComBuffer.java代码
package CommAccess;


public class ComBuffer
{
    private String Content = "";
    private String CurrentMsg, TempContent;
    private boolean available = false;
    private int LengthNeeded = 1;
    private int i = 0;

    // 读取一行数据,非阻塞
    public synchronized String GetMsg(int Length)
    {
        LengthNeeded = Length;
        notifyAll();
        if (LengthNeeded > Content.length())
        {
            
            available = false;
            while (available == false)
            {
                try
                {
                    wait(1000);
                    i++;
                    //System.out.println("第"+i+"次等待");
                    if(i>5){
                        CurrentMsg="overtime";
                        return CurrentMsg;
                    }
                 }
                catch (InterruptedException e) { }
            }
        }
        CurrentMsg  = Content.substring(0, LengthNeeded);
        TempContent = Content.substring(LengthNeeded);
        Content = TempContent;
        LengthNeeded = 1;
        notifyAll();
        return CurrentMsg;   
    }
    // 将一个字符保存到串口缓充区
    public synchronized void PutChar(int c)
    {
        Character d = new Character((char) c);
        Content = Content.concat(d.toString());
        if (LengthNeeded < Content.length())
        {
            available = true;
        }
        notifyAll();
   
    }
}
ReadCom.java代码
package CommAccess;

import
import

public class ReadCom extends Thread
{
    private ComBuffer ComBuffer;
    private InputStream ComPort;
    public ReadCom(ComBuffer CB, InputStream Port)
    {
        ComBuffer = CB;
        ComPort = Port;
    }
    public void run()
    {
        int c;
        try
        {
            while (true)
            {
                c = ComPort.read();      
                ComBuffer.PutChar(c);
            }
        } catch (IOException e) {}
    }
}
这到底是为什么读取不了串口的数据
希望高手能帮忙,我是个新手
我QQ869440098


[ 本帖最后由 妖孽玉流星 于 2011-5-1 19:19 编辑 ]
搜索更多相关主题的帖子: java 聊天工具 
2011-05-01 19:17
快速回复:java 基于串口的聊天工具读写不了串口中的数据(类似于QQ)(求助)
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.025628 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved