ディレクトリ 検索
android Manifest Manifest.permission Manifest.permission_group android.accessibilityservice AccessibilityService android.accounts Account android.app NotificationManager android.bluetooth BluetoothAdapter BluetoothClass BluetoothClass.Device BluetoothClass.Device.Major BluetoothClass.Service BluetoothDevice BluetoothServerSocket BluetoothSocket android.content SharedPreferences android.database.sqlite SQLiteCursorDriver SQLiteOpenHelper android.graphics Bitmap android.location LocationListener Geocoder GpsStatus GpsStatus.Listener GpsStatus.NmeaListener GpsSatellite android.media AudioFormat AsyncPlayer AudioRecord AudioRecord.OnRecordPositionUpdateListener ThumbnailUtils AudioManager android.net TrafficStats MailTo LocalSocket android.os AsyncTask AsyncTask.Status CountDownTimer Message MessageQueue HandlerThread android.text Html android.util JsonWriter android.view ContextMenu ContextMenu.ContextMenuInfo Display ViewManager View ViewStub ViewTreeObserver ViewParent WindowManager GestureDetector Gravity MenuInflater ScaleGestureDetector SoundEffectConstants android.view.inputmethod InputConnection InputMethod InputMethodSession BaseInputConnection InputMethodManager android.widget AbsListView AbsListView.LayoutParams AbsListView.OnScrollListener AbsListView.RecyclerListener AbsoluteLayout AbsoluteLayout.LayoutParams AbsSeekBar AbsSpinner AdapterView AdapterView.AdapterContextMenuInfo AdapterView.OnItemLongClickListener AdapterView.OnItemSelectedListener AdapterView.OnItemClickListener AnalogClock BaseAdapter BaseExpandableListAdapter Button CheckBox CheckedTextView Checkable Chronometer Chronometer.OnChronometerTickListener CompoundButton CompoundButton.OnCheckedChangeListener CursorAdapter CursorTreeAdapter DatePicker DatePicker.OnDateChangedListener DialerFilter DigitalClock EditText Filter Filter.FilterListener Filter.FilterResults ExpandableListAdapter ExpandableListView.OnChildClickListener ExpandableListView.OnGroupClickListener ExpandableListView.OnGroupCollapseListener ExpandableListView.OnGroupExpandListener Filterable Gallery Gallery.LayoutParams GridView GridLayout GridLayout.Alignment RadioGroup ImageView ImageView.ScaleType HorizontalScrollView ImageButton ImageSwitcher FilterQueryProvider ListAdapter ListView MediaController MultiAutoCompleteTextView MultiAutoCompleteTextView.CommaTokenizer MultiAutoCompleteTextView.Tokenizer QuickContactBadge RadioButton RatingBar RatingBar.OnRatingBarChangeListener RelativeLayout RemoteViews ResourceCursorAdapter ResourceCursorTreeAdapter Scroller ScrollView SearchView SearchView.OnCloseListener SearchView.OnQueryTextListener SearchView.OnSuggestionListener SeekBar SeekBar.OnSeekBarChangeListener SimpleAdapter SimpleAdapter.ViewBinder SimpleCursorAdapter SimpleCursorAdapter.CursorToStringConverter SimpleCursorAdapter.ViewBinder SimpleCursorTreeAdapter SimpleCursorTreeAdapter.ViewBinder SimpleExpandableListAdapter SlidingDrawer SlidingDrawer.OnDrawerCloseListener SlidingDrawer.OnDrawerOpenListener SlidingDrawer.OnDrawerScrollListener Spinner SpinnerAdapter WrapperListAdapter TabHost TabHost.TabSpec TextView TimePicker TimePicker.OnTimeChangedListener Toast TableLayout TableLayout.LayoutParams TableRow TableRow.LayoutParams TabWidget TextSwitcher ToggleButton TwoLineListItem VideoView ViewAnimator ViewFlipper ViewSwitcher ViewSwitcher.ViewFactory ZoomButtonsController ZoomButtonsController.OnZoomListener ZoomButton ZoomControls dalvik.system DexFile
テキスト


LocalSocket

版本:Android 4.0 r1

结构

继承关系

public classLocalSocketextendsObject

java.lang.Object

android.net.LocalSocket

类概述

UNIX域名空间内创建一个socket(非服务器),这种类型的socket完全不同于java.net.socket

构造函数

publicLocalSocket()

创建一个AF_LOCAL/UNIX套接字。

公共方法

public voidbind(LocalSocketAddress bindpoint)

绑定socket到一个端口。仅可由还没有被绑定的实体对象来调用该方法。

参数

bindpoint端口地址

异常

IOException

public voidclose()

关闭socket

异常

IOException

public voidconnect(LocalSocketAddress endpoint)

将当前socket连接到一个端口,只有当终端地址还没有被连接的情况下才能调用该函数。

参数

endpoint端口地址

异常

IOException如果socket是无效的或地址不存在

public voidconnect(LocalSocketAddress endpoint, int timeout)

将当前socket连接到一个端口。

异常

IOException如果socket是无效的或地址不存在

public FileDescriptor[]getAncillaryFileDescriptors()

获取一组由对端通过附加消息传送过来的文件描述符。这个方法会返回最近发送的文件描述符,并且返回空直到收到一个新的描述符文件描述符仅可以通过常规数据传送,此方法读取一个描述符后仅能返回非空值

返回值

空或者文件描符数组

异常

IOException

public FileDescriptorgetFileDescriptor()

返回文件描述符,如果文件没有打开或已关闭则返回空。

返回值

文件描述符或空

public InputStreamgetInputStream()

获取输入流

返回值

input stream

异常

socket已经关闭或者还没建立则抛出IO异常

public LocalSocketAddressgetLocalSocketAddress()

若存在则返回绑定的socket

返回值

本地socket地址,若匿名则返回空。

public OutputStreamgetOutputStream()

获取输出流

返回值

输出

异常

socket已经关闭或者还没建立则抛出IO异常

public CredentialsgetPeerCredentials()

获取socket对的认证信息。仅对已连接的套接字有效。

返回值

非空;认证信

异常

IOException

public intgetReceiveBufferSize()

(译者注:获取接受缓冲区大小)

异常

IOException

public LocalSocketAddressgetRemoteSocketAddress()

(译者注:获取socket连接端地址)

public intgetSendBufferSize()

(译者注:获取发送缓冲区大小)

异常

IOException

public intgetSoTimeout()

(译者注:得到远端超时设置)

异常

IOException

public synchronized booleanisBound()

(译者注:是否已经绑定)

public booleanisClosed()

(译者注:是否已经关闭连接)

public synchronized booleanisConnected()

(译者注:是否已连接)

public booleanisInputShutdown()

(译者注:输入流是否已关闭)

public booleanisOutputShutdown()

(译者注:输出流是否已关闭)

public voidsetFileDescriptorsForSend(FileDescriptor[] fds)

将一组文件描述符放入队列准备发送到对端(socket),这些文件描述符在下次发送普通数据时会作为单个辅助消息一同发送出去,请查看桌面linux系统的“main 7 unix”SCM_RIGHT

参数

Fds非空,待发送的文件描述符数组。

public voidsetReceiveBufferSize(int size)

(译者注:设置接受缓冲区大小)

异常

IOException

public voidsetSendBufferSize(int n)

(译者注:设置发送缓冲区大小)

异常

IOException

public voidsetSoTimeout(int n)

(译者注:设置远端超时设置)

异常

IOException

public voidshutdownInput()

关闭输入端socket

异常

IOException

public voidshutdownOutput()

关闭输出端socket

异常

IOException

补充

文章精选

[推荐]OPhone OS的网络层架构介绍

示例代码

Android LocalSocket / LocalServerSocket sample code

Platforms:Android SDK1.0 (Eclipse 3.4.1 + ADT 0.8.0)

main.xml

android:id="@+id/send_1_button"
android:layout_width="fill_parent"android:layout_height="wrap_content"
android:text="send 1 request"/>

java文件:

importjava.io.IOException;
importjava.io.InputStream;

importandroid.app.Activity;
importandroid.net.LocalServerSocket;
importandroid.net.LocalSocket;
importandroid.net.LocalSocketAddress;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.util.Log;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.Toast;

/**
*
* @author Denis Migol
*
*/
publicclassDemoActivityextendsActivity{

publicstaticStringSOCKET_ADDRESS="your.local.socket.address";

// background threads use this Handler to post messages to
// the main application thread
privatefinalHandlerhandler=newHandler();

publicclassNotificationRunnableimplementsRunnable{
privateStringmessage=null;

publicvoidrun(){
if(message!=null&&message.length()>0){
showNotification(message);
}
}

/**
* @param message the message to set
*/
publicvoidsetMessage(Stringmessage){
this.message=message;
}
}

// post this to the Handler when the background thread notifies
privatefinalNotificationRunnablenotificationRunnable=newNotificationRunnable();

publicvoidshowNotification(Stringmessage){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}

classSocketListenerextendsThread{
privateHandlerhandler=null;
privateNotificationRunnablerunnable=null;

publicSocketListener(Handlerhandler,NotificationRunnablerunnable){
this.handler=handler;
this.runnable=runnable;
this.handler.post(this.runnable);
}

/**
* Show UI notification.
* @param message
*/
privatevoidshowMessage(Stringmessage){
this.runnable.setMessage(message);
this.handler.post(this.runnable);
}

@Override
publicvoidrun(){
//showMessage("DEMO: SocketListener started!");
try{
LocalServerSocketserver=newLocalServerSocket(SOCKET_ADDRESS);
while(true){
LocalSocketreceiver=server.accept();
if(receiver!=null){
InputStreaminput=receiver.getInputStream();

// simply for java.util.ArrayList
intreaded=input.read();
intsize=0;
intcapacity=0;
byte[]bytes=newbyte[capacity];

// reading
while(readed!=-1){
// java.util.ArrayList.Add(E e);
capacity=(capacity*3)/2+1;
//bytes = Arrays.copyOf(bytes, capacity);
byte[]copy=newbyte[capacity];
System.arraycopy(bytes,0,copy,0,bytes.length);
bytes=copy;
bytes[size++]=(byte)readed;

// read next byte
readed=input.read();
}

showMessage(newString(bytes,0,size));
}
}
}catch(IOExceptione){
Log.e(getClass().getName(),e.getMessage());
}
}
}

publicstaticvoidwriteSocket(Stringmessage)throwsIOException{
LocalSocketsender=newLocalSocket();
sender.connect(newLocalSocketAddress(SOCKET_ADDRESS));
sender.getOutputStream().write(message.getBytes());
sender.getOutputStream().close();
}

@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

newSocketListener(this.handler,this.notificationRunnable).start();

Buttonsend1=(Button)findViewById(R.id.send_1_button);
send1.setOnClickListener(newOnClickListener(){

@Override
publicvoidonClick(Viewv){
try{
writeSocket("hello");
}catch(IOExceptione){
Log.e(getClass().getName(),e.getMessage());
}
}

});
}
}


前の記事: 次の記事: