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

📄 server.java

📁 蓝牙聊天,带表情! 自定义组件,美观,大方!
💻 JAVA
字号:
package com.bt;

import java.io.*;
import java.util.Vector;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;

public class Server extends Form implements CommandListener, Runnable {
	
    private TextField tfData = new TextField("请输入发送的消息","",255,TextField.ANY);
    private MessageArea messageArea = null;;
    private Command cmdSend = new Command("发送", Command.ITEM, 0);
    private Command cmdQQ = new Command("表情", Command.ITEM, 1);
    private Command cmdExit = new Command("退出", Command.EXIT, 1);
	private StreamConnectionNotifier server = null;
	private Vector messages = new Vector();
    private DataInputStream dis = null;
    private DataOutputStream dos = null;
    private boolean isRunning = true;
    public static Server btServer = null;

	public Server(String title) {
		// TODO Auto-generated constructor stub
		super(title);
		btServer = this;
		messageArea = new MessageArea(null,tfData.getMinimumHeight());
        this.append(tfData);
        this.append(messageArea);
        this.addCommand(cmdExit);
        this.addCommand(cmdSend);
        this.setCommandListener(this);  
        new Thread(this).start();
	}

	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 == cmdQQ){
        	ChoiceQQ.setPosition("Server");
        	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;
        try {
            LocalDevice local = LocalDevice.getLocalDevice();
            local.setDiscoverable(DiscoveryAgent.GIAC);
            chatMessage("开启本地服务被查找...");
        } catch (BluetoothStateException e) {
            return;
        }
        BTMIDlet.display.setCurrent(this);//防止阶界面返回
        try {
            server = (StreamConnectionNotifier)Connector.open(
                "btspp://localhost:11111111111111111111111111111111");//返回本机L2CAPConnectionNotifier
        } catch (IOException e) {
            return;
        }
        BTMIDlet.display.setCurrent(this);//防止阶界面返回
        String message = "";
        while(isRunning) {		//防止中途退出再连接
        	StreamConnection conn = null;
        	try {
        		try {
        			conn = server.acceptAndOpen();			//返回一个服务器端的套接字连接
        			chatMessage("对方已经连接...");
        			this.addCommand(cmdQQ);
        		} catch (IOException e) {
        			return;
        		}
        		dis = conn.openDataInputStream();
        		dos = conn.openDataOutputStream();
        		while(isRunning) {
        			message = dis.readUTF();
        			chatMessage("对方",message);
        			messageArea.refresh();
        			Thread.sleep(1000);
        		}
        		
        	} catch (Exception e) {
        		e.printStackTrace();
        	} finally {
        		if (conn!=null) {
        			try {
        				conn.close();
        				conn = null;
        			}catch (Exception e) {
        			}
        		}
        		this.removeCommand(cmdQQ);
        	}
        }
	}
	
	 public void close() {
	        try {
	            if (dis != null) {
	            	dis.close();
	            	dis = null;
	            }
	            if (dos != null) {
	            	dos.close();
	            	dos = null;
	            }
	            if (server != null) {
	            	server.close();
	            	server = null;
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	 
		public void chatMessage(String userName,String msg) {
			messages.addElement(userName+"说:"+msg);
			messageArea.refresh();
		}
		public void chatMessage(String 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 > Server.this.getHeight())
					this.mnHeight = Server.this.getHeight() / 4;
				else
					this.mnHeight = mnHeight;
			}
			
			protected int getMinContentHeight() {
				// TODO Auto-generated method stub
				return Server.this.getHeight() - mnHeight-Font.getDefaultFont().getHeight();
			}

			protected int getMinContentWidth() {
				// TODO Auto-generated method stub
				return Server.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);
				
				synchronized (messages) {
					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 = Server.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 = Server.this.getWidth();
				int strWidth = f.stringWidth(msg);
				int rows = strWidth / maxWidth;
				if ((strWidth % maxWidth) > 0)
					rows++;
				return rows;
			}
	 }
}

⌨️ 快捷键说明

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