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

📄 gameclient.java

📁 支持蓝牙的手机游戏 支持蓝牙的手机游戏的分析与实现
💻 JAVA
字号:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package org.challenge.chengshi.game.client;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.util.Enumeration;import java.util.Hashtable;import java.util.Vector;import javax.bluetooth.BluetoothStateException;import javax.bluetooth.DeviceClass;import javax.bluetooth.DiscoveryAgent;import javax.bluetooth.DiscoveryListener;import javax.bluetooth.LocalDevice;import javax.bluetooth.RemoteDevice;import javax.bluetooth.ServiceRecord;import javax.bluetooth.UUID;import javax.microedition.io.Connector;import javax.microedition.io.StreamConnection;import org.challenge.chengshi.game.GameUI;/** * * @author challenge */public class GameClient implements DiscoveryListener {    GameUI game;    String message;    StreamConnection conn;    DataInputStream in;    DataOutputStream out;    Thread read;    Thread write;    boolean searchFinished=false;    RemoteDevice remoteDevice;    String uuidString="F0E0D0C0B0A000908070605040302010";    /** Keeps the discovery agent reference. */    private DiscoveryAgent discoveryAgent;    /** Keeps the device discovery return code. */    private int discType;    Hashtable remoteDevices=new Hashtable();    ServiceRecord serviceRecord;    String url=null;    boolean exitFlag;    boolean BTReady;    Hashtable services=new Hashtable();    Vector vectorURL=new Vector();    Vector vectorName=new Vector();        public GameClient(GameUI game){        this.game=game;//        th=new Thread(this); //       th.start();    }    //通过写线程进行发送信息    public void sendMessage(String message){        if(this.write==null){            return;        }        this.message=message;        synchronized(this.write){            this.write.notify();//唤醒写线程        }    }    //对方发信息,接收    public void recevieMessage(String message){        this.game.receiveMessage(message);    }    //搜索蓝牙设备和服务    public void search(){        try{            boolean isBTReady = false;        try {            // create/get a local device and discovery agent            LocalDevice localDevice = LocalDevice.getLocalDevice();            localDevice.setDiscoverable(DiscoveryAgent.GIAC);            discoveryAgent = localDevice.getDiscoveryAgent();            isBTReady = true;        } catch (Exception e) {            System.err.println("Can't initialize bluetooth: " + e);        }        // nothing to do if no bluetooth available        if (!isBTReady) {            return;        }            this.remoteDevices.clear();            this.services.clear();            this.vectorURL.removeAllElements();            this.vectorName.removeAllElements();            this.searchFinished=false;            //开始搜索设备            this.discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);        }catch(BluetoothStateException e){            e.printStackTrace();        }    }        public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {        //每发现一个设备就向remoteDevices中添加一个        this.remoteDevices.put(btDevice.getBluetoothAddress(), btDevice);    }    //服务发现方法回调    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {        try {            if (servRecord == null || servRecord.length == 0) {                url = null;                this.serviceRecord = null;                return;            }            this.serviceRecord = servRecord[0];            url = this.serviceRecord.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);            this.vectorURL.addElement(url);            this.vectorName.addElement(this.remoteDevice.getFriendlyName(false));            this.services.put( this.remoteDevice.getFriendlyName(false), this.url);//发现有本服务就添加一个url        } catch (Exception ex) {            ex.printStackTrace();        }    }    //服务发现完毕    public void serviceSearchCompleted(int transID, int respCode) {        // ok, all of the transactions are completed        searchFinished=true;        synchronized (this) {            notifyAll();        }    }    //设备搜索完毕    public void inquiryCompleted(int discType) {        this.discType = discType;        try {                        this.searchServices(this.remoteDevices);                  } catch (BluetoothStateException ex) {            ex.printStackTrace();        }        this.remoteDevices.clear();    }    //开始对发现的每一个设备进行搜索服务    private void searchServices(Hashtable remotes) throws BluetoothStateException {        UUID[] UUIDs=new UUID[2];        UUIDs[1]=new UUID(this.uuidString,false);        UUIDs[0]=new UUID(0x0003);        for(Enumeration e=remotes.keys();e.hasMoreElements();){            String key=(String)e.nextElement();            remoteDevice=(RemoteDevice)remotes.get(key);            this.discoveryAgent.searchServices(null, UUIDs, remoteDevice, this);        }    }    //获得服务端的名字列表    public Enumeration getRemoteName(){        //搜索完毕时才可返回        while(this.searchFinished==false){}        return this.vectorName.elements();    }        public void connect(String name){        this.url=(String)this.services.get(name);        new Connect();    }    //连接到服务端的线程类    class Connect implements Runnable{        public Connect(){            Thread th=new Thread(this);            th.start();        }        public void run() {            try {                conn = (StreamConnection) Connector.open(url);                in = conn.openDataInputStream();                out = conn.openDataOutputStream();                read = new Read();                write = new Write();                read.start();                write.start();                BTReady = true;             } catch (IOException ex) {                ex.printStackTrace();             }        }    }            //读服务器端发送过来的信息    class Read extends Thread{        public void run(){            while(true){                try {                    String str = in.readUTF();                    if (str != null) {//接收到的信息不为空时才回调                        game.receiveMessage(str);                    }                } catch (IOException ex) {                    ex.printStackTrace();                }            }        }    }    //向服务端发送信息    class Write extends Thread{                public void run(){            while(true){                synchronized(this){                    try{                        wait();//无信息可发送时一直等待,有信息可发送时才唤醒本线程                    }catch(InterruptedException e){                        e.printStackTrace();                    }                    if(message!=null){                        try {                            out.writeUTF(message);                        } catch (IOException ex) {                            ex.printStackTrace();                        }                    }                }            }        }    }}

⌨️ 快捷键说明

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