?? bluetoothconnection.java
字號:
package game.bluetooth;
import javax.microedition.io.*;
import java.io.*;
public class BluetoothConnection
{
private StreamConnection streamConnection;
private InputStream inputStream;
private OutputStream outputStream;
private String localName; // 此連接的本地設備名
private String remoteName; // 此連接的遠端設備名
private String url; // url字符串,用來建立連接用
public BluetoothConnection(StreamConnection con, String ln, String rn)
throws IOException
{
localName = ln;
remoteName = rn;
url = "";
streamConnection = con;
openStreams();
}
public BluetoothConnection(String urlStrings, String ln, String rn)
throws IOException
{
localName = ln;
remoteName = rn;
url = urlStrings;
connect();
}
private void connect()
throws IOException
{
streamConnection = (StreamConnection) Connector.open( url );
openStreams();
}
private void openStreams()
throws IOException
{
inputStream = streamConnection.openInputStream();
outputStream = streamConnection.openOutputStream();
}
synchronized public void close()
{
try
{
outputStream.close();
}
catch(IOException e)
{ }
try
{
inputStream.close();
}
catch(IOException e)
{ }
try
{
if(streamConnection != null)
{
streamConnection.close();
streamConnection = null;
}
}
catch( IOException e )
{ }
}
public InputStream getInputStream()
{
return inputStream;
}
public OutputStream getOutputStream()
{
return outputStream;
}
public String getLocalName()
{
return localName;
}
public String getRemoteName()
{
return remoteName;
}
protected void setRemoteName( String rn )
{
//設置遠端連接的名稱
remoteName = rn;
}
protected void setLocalName( String ln)
{
localName = ln;
}
/**
* 傳送一個字符串到遠端設備
* 必須首先傳送字符串長度
*/
public void writeString(String s)
throws IOException
{
byte[] bytes = s.getBytes();
outputStream.write(bytes.length);
outputStream.write(bytes);
outputStream.flush();
}
/**
* 讀取遠端設備發送來的字符串
* 必須首先讀入字符串長度
*/
public String readString()
throws IOException
{
int length = inputStream.read();
byte[] bytes = new byte[length];
read(bytes, length);
return new String(bytes);
}
/**
* 寫一個整數
*/
public void writeInt( int v )
throws IOException
{
outputStream.write( (v & 0xFF) );
outputStream.write( ((v>>8) & 0xFF) );
outputStream.write( ((v>>16) & 0xFF) );
outputStream.write( ((v>>24) & 0xFF) );
}
/**
* 讀一個整數
*/
public int readInt()
throws IOException
{
int res;
res = inputStream.read();
res += inputStream.read()<<8;
res += inputStream.read()<<16;
res += inputStream.read()<<24;
return res;
}
public boolean isClosed()
{
if( streamConnection == null )
{
//己斷開
return true;
}
else
{
//仍然連接
return false;
}
}
/**
* 讀取bytes到數組中,直到讀入len個byte。
*/
public void read( byte[] arr, int len )
throws IOException
{
int offs, count;
offs = 0;
while( len > 0 )
{
// 仍有需要讀入的byte
count = inputStream.read( arr, offs, len );
len -= count;
offs += count;
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -