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

📄 serverbox.java

📁 《Java ME手机应用开发大全》源码 書籍內容簡介: http://www.china-pub.com/410
💻 JAVA
字号:
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.IOException; 

import java.util.Vector; 

import javax.bluetooth.DiscoveryAgent; 
import javax.bluetooth.LocalDevice; 
import javax.bluetooth.ServiceRecord; 
import javax.bluetooth.UUID; 
import javax.microedition.io.Connector; 
import javax.microedition.io.StreamConnection; 
import javax.microedition.io.StreamConnectionNotifier; 

import javax.microedition.lcdui.Command; 
import javax.microedition.lcdui.CommandListener; 
import javax.microedition.lcdui.Displayable; 

import javax.microedition.lcdui.TextBox; 
import javax.microedition.lcdui.TextField; 

/** 
 * 服务端GUI 
 */ 
public class ServerBox extends TextBox implements Runnable, CommandListener { 

    Command com_pub = new Command("开启服务", Command.OK, 0); 
    Command com_cancel = new Command("终止服务", Command.CANCEL, 0); 
    Command com_back = new Command("返回", Command.BACK, 1); 
    //声明本地设备实例
    LocalDevice localDevice; 
    StreamConnectionNotifier notifier; 
    ServiceRecord record; 
    boolean isClosed; 
    ClientProcessor processor; 

    BTMIDlet midlet; 
    //响应服务的uuid 
    private static final UUID ECHO_SERVER_UUID = new UUID( 
            "F0E0D0C0B0A000908070605040302010", false); 

    public ServerBox(BTMIDlet midlet) { 
        super(null, "", 500, TextField.ANY); 
        this.midlet = midlet; 
        this.addCommand(com_pub); 
        this.addCommand(com_back); 
        this.setCommandListener(this); 
    } 


    public void run() { 
        boolean isBTReady = false; 

        try { 

            localDevice = LocalDevice.getLocalDevice(); 

            if (!localDevice.setDiscoverable(DiscoveryAgent.GIAC)) { 
                showInfo("无法设置设备发现模式"); 
                return; 
            } 

            //创建用于作为连接URL的字符缓冲区对象  
            StringBuffer url = new StringBuffer("btspp://"); 

            // 添加服务器的IP
            url.append("localhost").append(':'); 

            // 添加服务的 UUID 
            url.append(ECHO_SERVER_UUID.toString()); 

            // 添加服务的名称
            url.append(";name=Echo Server");          
            // 所有连接的客户端不需要认证
            url.append(";authorize=false"); 

            // 创建并打开蓝牙服务连接
            notifier = (StreamConnectionNotifier) Connector.open(url.toString()); 
            record = localDevice.getRecord(notifier); 
			//设置连接成功的标志为
            isBTReady = true; 
        } catch (Exception e) { 
            e.printStackTrace(); 
             
        } 

        // 显示连接成功的见面
        if (isBTReady) { 
            showInfo("初始化成功,等待连接"); 
            this.removeCommand(com_pub); 
            this.addCommand(com_cancel); 
        } else { 
            showInfo("初始化失败,退出"); 
            return; 

        } 

        // 生成服务端服务线程对象 
        processor = new ClientProcessor(); 

        // 建立连接
        while (!isClosed) { 
            StreamConnection conn = null; 

            try { 
                conn = notifier.acceptAndOpen(); 
            } catch (IOException e) { 
                continue; 
            } 
            processor.addConnection(conn); 
        } 

    } 

    public void publish() { 
        isClosed = false; 
        this.setString(null); 
        new Thread(this).start(); 

    } 

    public void cancelService() { 
        isClosed = true; 
        showInfo("服务终止"); 
        this.removeCommand(com_cancel); 
        this.addCommand(com_pub); 
    } 

    public void commandAction(Command arg0, Displayable arg1) { 
        if (arg0 == com_pub) { 
            //发布service 
            publish(); 
        } else if (arg0 == com_cancel) { 
            cancelService(); 
        } else { 
            cancelService(); 
            midlet.showMainMenu(); 
        } 

    } 
     
    /** 
     * 内部类,服务端服务线程。 
     */ 
    private class ClientProcessor implements Runnable { 
        private Thread processorThread; 

        private Vector queue = new Vector(); 

        private boolean isOk = true; 

        ClientProcessor() { 
            processorThread = new Thread(this); 
            processorThread.start(); 
        } 

        public void run() { 
            while (!isClosed) { 

                synchronized (this) { 
                    if (queue.size() == 0) { 
                        try { 
                            //阻塞,直到有新客户连接 
                            wait(); 
                        } catch (InterruptedException e) { 

                        } 
                    } 
                } 
                //处理连接队列 
                StreamConnection conn; 
                synchronized (this) { 

                    if (isClosed) { 
                        return; 
                    } 
                    conn = (StreamConnection) queue.firstElement(); 
                    queue.removeElementAt(0); 
                    processConnection(conn); 
                } 
            } 
        } 
         
        /** 
         * 往连接队列添加新连接,同时唤醒处理线程  
         */ 

        void addConnection(StreamConnection conn) { 
            synchronized (this) { 
                queue.addElement(conn); 
                notify(); 
            } 
        } 

    } 

    /** 
     * 从StreamConnection读取输入 
     */ 
    private String readInputString(StreamConnection conn) { 
        String inputString = null; 

        try { 

            DataInputStream dis = conn.openDataInputStream(); 
            inputString = dis.readUTF(); 
            dis.close(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return inputString; 
    } 
 
    private void showInfo(String s) { 
        StringBuffer sb = new StringBuffer(this.getString()); 
        if (sb.length() > 0) { 
            sb.append("\n"); 
        } 

        sb.append(s); 
        this.setString(sb.toString()); 

    } 
     

    /** 
     * 处理客户端连接 
     */     
    private void processConnection(StreamConnection conn) { 

        // 读取输入 
        String inputString = readInputString(conn); 
        //生成响应 
        String outputString = inputString.toUpperCase(); 
        //输出响应 
        sendOutputData(outputString, conn); 

        try { 
            conn.close(); 
        } catch (IOException e) { 
        }  
        showInfo("客户端输入:" + inputString + ",已成功响应!"); 
    } 
     
    /** 
     * 输出响应 
     */ 

    private void sendOutputData(String outputData, StreamConnection conn) { 

        try { 
            DataOutputStream dos = conn.openDataOutputStream(); 
            dos.writeUTF(outputData); 
            dos.close(); 
        } catch (IOException e) { 
        } 

    } 
} 

⌨️ 快捷键说明

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