📄 client.java
字号:
package com.bt;
import java.io.*;
import java.util.Vector;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
public class Client extends Form implements CommandListener,Runnable {
private TextField tfData = new TextField("请输入发送的消息", "",255,TextField.ANY);
private MessageArea messageArea = null;;
private Command cmdExit = new Command("退出", Command.EXIT, 0);
private Command cmdSend = new Command("发送", Command.ITEM, 2);
private Command cmdConnect = new Command("连接", Command.ITEM, 1);
private Command cmdQQ = new Command("表情", Command.ITEM, 3);
private StreamConnection client = null;
private Vector messages = new Vector();
private ServiceRecord record = null;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean isRunning = true;
public static Client btClient = null;
public Client(String title) {
// TODO Auto-generated constructor stub
super(title);
this.append(tfData);
messageArea = new MessageArea(null,tfData.getMinimumHeight());
this.append(messageArea);
this.addCommand(cmdExit);
this.addCommand(cmdConnect);
this.setCommandListener(this);
btClient = this;
}
public void commandAction(Command c, Displayable d) {
// TODO Auto-generated method stub
if (c == cmdExit) {
isRunning = false;
BTMIDlet.midlet.notifyDestroyed();
} else if(c == cmdSend) {
//发送数据
new Thread() {
public void run() {
if (dos == null) {
return;
}
String str = tfData.getString();
tfData.setString("");
chatMessage("自己",str);
writeInfo(str);
}
}.start();
} else if (c == cmdConnect) {
new Thread(this).start();
}else if(c == cmdQQ){
ChoiceQQ.setPosition("Client");
BTMIDlet.display.setCurrent(BTMIDlet.qq);
}
}
public void writeInfo(String str){
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
// TODO Auto-generated method stub
isRunning = true;
chatMessage("正在获取,请稍后...");
MyDiscoveryListener ml = new MyDiscoveryListener();
record = ml.searchRemoteDevice();
if(record == null){
return;
}
StreamConnection con = null;
String URL = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
try {
con = (StreamConnection) Connector.open(URL);
dis = con.openDataInputStream();
dos = con.openDataOutputStream();
this.removeCommand(cmdConnect);
this.addCommand(cmdSend);
this.addCommand(cmdQQ);
BTMIDlet.display.setCurrent(this); //防止阶界面返回
chatMessage("成功连接!");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(isRunning) {
try {
String message = dis.readUTF();
chatMessage("对方",message);
messageArea.refresh();
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
break;
}
}
close();
removeCommand(cmdSend);
addCommand(cmdConnect);
}
public void close() {
try {
if (dis != null) {
dis.close();
dis = null;
}
if (dos != null) {
dos.close();
dos = null;
}
if (client != null) {
client.close();
client = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
class MyDiscoveryListener implements DiscoveryListener {
// 用于保存搜索到的设备
Vector devices = new Vector();
//本地设备的发现代理
private DiscoveryAgent agent;
// 服务UUID
UUID[] searchList = {new UUID("11111111111111111111111111111111", false)};
// 服务器服务记录
private ServiceRecord record;
ServiceRecord searchRemoteDevice() {
LocalDevice ld=null;
try {
ld = LocalDevice.getLocalDevice();
} catch (BluetoothStateException e1) {
e1.printStackTrace();
return null;
}
agent = ld.getDiscoveryAgent();
RemoteDevice[] devList = agent.retrieveDevices(DiscoveryAgent.CACHED);
// 搜索所有的设备
try {
agent.startInquiry(DiscoveryAgent.GIAC, this);
} catch (BluetoothStateException e) {
e.printStackTrace();
}
// 等待所有设备被发现后再继续搜索服务
synchronized (this) {
try {
this.wait();
} catch (Exception e) {
}
}
if (devices.size() > 0) {
devList = new RemoteDevice[devices.size()];
devices.copyInto(devList);
if (searchServices(devList)) {
return record;
}
}
return null;
}
boolean searchServices(RemoteDevice[] devList) {
// 逐个搜索设备
for (int i = 0; i < devList.length; i++) {
try {
agent.searchServices(null, searchList, devList[i],
this);
} catch (BluetoothStateException e) {
}
// 一次执行一个搜索
synchronized (this) {
try {
this.wait();
} catch (Exception e) {
}
}
if (record != null) {
return true;
}
}
return false;
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
devices.addElement(btDevice);
}
public void inquiryCompleted(int discType) {
// 查询结束后通知searchRemoteDevice继续执行
synchronized (this) {
try {
this.notifyAll();
} catch (Exception e) {
}
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
// 保存服务记录
record = servRecord[0];
synchronized (this) {
this.notifyAll();
}
}
public void serviceSearchCompleted(int transID, int responseCode) {
synchronized (this) {
this.notifyAll();
}
}
}
public void chatMessage(String userName,String msg) {
messages.addElement(userName+"说:"+msg);
messageArea.refresh();
}
public void chatMessage(String msg) {
messages.addElement(msg);
messageArea.refresh();
}
public void chatMessage(Image msg) {
messages.addElement(msg);
messageArea.refresh();
}
class MessageArea extends CustomItem{
private int mnHeight;
private Font font = Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_PLAIN, Font.SIZE_MEDIUM);
public MessageArea(String label, int mnHeight) {
super(label);
if (this.mnHeight > Client.this.getHeight())
this.mnHeight = Client.this.getHeight() / 4;
else
this.mnHeight = mnHeight;
}
protected int getMinContentHeight() {
// TODO Auto-generated method stub
return Client.this.getHeight() - mnHeight-Font.getDefaultFont().getHeight();
}
protected int getMinContentWidth() {
// TODO Auto-generated method stub
return Client.this.getWidth();
}
protected int getPrefContentHeight(int arg0) {
// TODO Auto-generated method stub
return getMinContentHeight();
}
protected int getPrefContentWidth(int arg0) {
// TODO Auto-generated method stub
return getMinContentWidth();
}
protected void paint(Graphics g, int w, int h) {
// TODO Auto-generated method stub
g.setColor(123,163,3);
g.fillRect(0, 0, w, h);
g.setColor(0xffffff);
g.setFont(font);
// 画信息
int rowsLeft = getMinimumHeight() / font.getHeight();
if ((getMinimumHeight() % font.getHeight()) > 0)
rowsLeft--;
for (int msgIdx = messages.size() - 1; rowsLeft >= 0
&& msgIdx >= 0; msgIdx--) {
rowsLeft -= drawMessage(g, font, messages.elementAt(msgIdx)
.toString(), rowsLeft);
}
}
public void refresh(){
repaint();
}
private int drawMessage(Graphics g, Font f, String msg, int rowsLeft) {
int maxWidth = Client.this.getWidth();
int begin = 0, end = 0;
int rows = getApproximationOfRowCount(f, msg);
for (int rowIdx = 0; rowIdx < rows; rowIdx++) { //遍历每一行
for (;end <= msg.length()&& f.substringWidth(msg, begin, end
- begin) < maxWidth; end++)
;//内容长度小等于内容总长度同时满足字体要画作息的长度小于屏幕宽度
end--;
if(msg.indexOf("<:=")!=-1&&msg.indexOf(":>")!=-1){
for(int i=0;i<BTMIDlet.imgQQ.length;i++){
if(msg.substring(msg.indexOf("<:="),msg.indexOf(":>")+(msg.indexOf(":>")-msg.indexOf("<:="))/2).equals("<:="+i+":>")){
g.drawImage(BTMIDlet.imgQQ[i], f.stringWidth("自己说:"),
(rowsLeft - rows + rowIdx) * f.getHeight(),
Graphics.TOP | Graphics.LEFT);
end -= 7;
}
}
}
g.drawSubstring(msg, begin, end - begin, 0,
(rowsLeft - rows + rowIdx) * f.getHeight(),
Graphics.TOP | Graphics.LEFT);
begin = end;
}
return rows;
}
private int getApproximationOfRowCount(Font f, String msg) {//四舍五入返回信息有多少行
int maxWidth = Client.this.getWidth();
int strWidth = f.stringWidth(msg);
int rows = strWidth / maxWidth;
if ((strWidth % maxWidth) > 0)
rows++;
System.out.println(maxWidth);
return rows;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -