?? clientprocessor.java
字號:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
import javax.bluetooth.ServiceRecord;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
public class ClientProcessor implements Runnable{
private volatile boolean isReady;
private Client client;
private ServiceRecord serviceRecord;
private int requiredSecurity= ServiceRecord.NOAUTHENTICATE_NOENCRYPT;
private StreamConnection connection;
private InputStream in;
private OutputStream out;
private Vector sendMessages=new Vector();;
public ClientProcessor(Client client,ServiceRecord serviceRecord){
this.client=client;
this.serviceRecord = serviceRecord;
}
public synchronized void start() {
Thread thread = new Thread(this);
thread.start();
}
public ServiceRecord getServiceRecord() {
return serviceRecord;
}
public void run() {
// the reader
// 1. open the connection and streams, start the writer
String url = null;
try
{
// 'must be master': false
url = serviceRecord.getConnectionURL(requiredSecurity,false);
connection = (StreamConnection) Connector.open(url);
in = connection.openInputStream();
out = connection.openOutputStream();
// start the writer
Write write = new Write();
Thread writeThread = new Thread(write);
writeThread.start();
}
catch(IOException e)
{
close();
return;
}
catch (SecurityException e)
{
close();
return;
}
// 2. wait to receive and read messages
while (!isReady)
{
try
{
byte[] temp=new byte[4];
//println("=======================client1");
in.read(temp);
client.read(temp);
}
catch (Exception e)
{
close();
}
}
}
public void close() {
if (!isReady)
{
synchronized(this)
{
isReady = true;
}
synchronized(sendMessages)
{
sendMessages.notify();
}
if (out != null)
{
try
{
out.close();
synchronized (this)
{
out = null;
}
}
catch(IOException e)
{
// there is nothing we can do: ignore it
}
}
if (in != null)
{
try
{
in.close();
synchronized (this)
{
in = null;
}
}
catch(IOException e)
{
// there is nothing we can do: ignore it
}
}
if (connection != null)
{
try
{
connection.close();
synchronized (this)
{
connection = null;
}
}
catch (IOException e)
{
// there is nothing we can do: ignore it
}
}
}
}
private class Write implements Runnable{
public Write() {
}
public void run() {
// TODO 自動生成方法存根
while(!isReady){
synchronized(sendMessages){
try{
byte[] temp=((String)sendMessages.elementAt(0)).getBytes();
out.write(temp);
out.flush();
sendMessages.removeElementAt(0);
}catch(Exception e){
// close();
}
if(sendMessages.size()==0){
try{
sendMessages.wait();
}catch (InterruptedException ex){}
}
}
}
}
}
public void send(String data){
synchronized(sendMessages){
try{
sendMessages.addElement(data);
//println(sendMessages);
sendMessages.notify();
}catch(Exception e){e.printStackTrace();}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -