annuaire recherche
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
personnages


LocalSocket

 版本:Android 4.0 r1

 

结构

继承关系

public class LocalSocket extends Object

        

java.lang.Object

android.net.LocalSocket

 

类概述

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

 

构造函数

public LocalSocket ()

         创建一个AF_LOCAL/UNIX 套接字。

 

公共方法

public void bind (LocalSocketAddress bindpoint)

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

参数

bindpoint    端口地址

异常

IOException

 

public void close ()

关闭socket

异常

IOException

 

public void connect (LocalSocketAddress endpoint)

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

         参数

endpoint     端口地址

         异常

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

 

public void connect (LocalSocketAddress endpoint, int timeout)

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

异常

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

 

public FileDescriptor[] getAncillaryFileDescriptors()

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

         返回值

空或者文件描符数组

         异常

IOException

 

public FileDescriptor getFileDescriptor ()

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

返回值

文件描述符或空

 

public InputStream getInputStream ()

         获取输入流

         返回值

input stream

         异常

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

public LocalSocketAddress getLocalSocketAddress ()

若存在则返回绑定的socket

         返回值

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

 

public OutputStream getOutputStream ()

获取输出流

         返回值

输出

         异常

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

 

public Credentials getPeerCredentials ()

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

返回值

非空; 认证信

         异常

IOException

 

public int getReceiveBufferSize ()

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

         异常

IOException

 

public LocalSocketAddress getRemoteSocketAddress()

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

 

public int getSendBufferSize ()

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

         异常

IOException

 

public int getSoTimeout ()

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

         异常

IOException

 

public synchronized boolean isBound ()

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

 

public boolean isClosed ()

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

 

public synchronized boolean isConnected ()

(译者注:是否已连接)

 

public boolean isInputShutdown ()

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

 

public boolean isOutputShutdown ()

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

 

public void setFileDescriptorsForSend(FileDescriptor[] fds)

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

参数

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

 

public void setReceiveBufferSize (int size)

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

         异常

IOException

 

public void setSendBufferSize (int n)

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

         异常

IOException

 

public void setSoTimeout (int n)

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

         异常

IOException

 

public void shutdownInput ()

关闭输入端socket

   异常

   IOException

 

public void shutdownOutput ()

关闭输出端socket

异常

IOException

 

 

补充 

文章精选

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

示例代码

    Android LocalSocket / LocalServerSocket sample code

Platforms: Android SDK 1.0 (Eclipse 3.4.1 + ADT 0.8.0)

main.xml

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

 

java文件:

import java.io.IOException;
import java.io.InputStream;

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

/**
*
* @author Denis Migol
*
*/
public class DemoActivity extends Activity {
   
    public static StringSOCKET_ADDRESS = "your.local.socket.address";
   
    // background threads use this Handler to post messages to
    // the main application thread
    private final Handlerhandler = new Handler();
   
    public class NotificationRunnable implements Runnable {
        private Stringmessage = null;
       
        public void run() {
           if (message != null &&message.length() > 0) {
                showNotification(message);
           }
        }
       
        /**
        * @param message the message to set
        */
        public voidsetMessage(String message) {
           this.message =message;
        }
    }
   
    // post this to the Handler when the background thread notifies
    private final NotificationRunnablenotificationRunnable = new NotificationRunnable();
   
    public voidshowNotification(String message) {
        Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
    }
   
    class SocketListener extends Thread {
        private Handlerhandler = null;
        private NotificationRunnablerunnable = null;
       
        public SocketListener(Handlerhandler, NotificationRunnablerunnable) {
           this.handler =handler;
           this.runnable =runnable;
           this.handler.post(this.runnable);
        }
       
        /**
        * Show UI notification.
        * @param message
        */
        private voidshowMessage(String message) {
           this.runnable.setMessage(message);
           this.handler.post(this.runnable);
        }
       
        @Override
        public void run() {
           //showMessage("DEMO: SocketListener started!");
           try {
               LocalServerSocket server = new LocalServerSocket(SOCKET_ADDRESS);
               while (true) {
                    LocalSocketreceiver = server.accept();
                   if (receiver != null) {
                       InputStream input =receiver.getInputStream();
                       
                       // simply for java.util.ArrayList
                        intreaded = input.read();
                       int size = 0;
                       int capacity = 0;
                       byte[] bytes = new byte[capacity];
                       
                       // reading
                        while (readed!= -1) {
                           // java.util.ArrayList.Add(E e);
                            capacity = (capacity * 3)/2 + 1;
                           //bytes = Arrays.copyOf(bytes, capacity);
                           byte[] copy = new byte[capacity];
                           System.arraycopy(bytes, 0, copy, 0, bytes.length);
                            bytes = copy;
                            bytes[size++] = (byte)readed;
                           
                            // read next byte
                            readed = input.read();
                       }
                       
                        showMessage(new String(bytes, 0, size));
                   }
               }
           } catch (IOException e) {
               Log.e(getClass().getName(), e.getMessage());
           }
        }
    }
   
    public static voidwriteSocket(String message) throws IOException {
        LocalSocketsender = new LocalSocket();
        sender.connect(new LocalSocketAddress(SOCKET_ADDRESS));
        sender.getOutputStream().write(message.getBytes());
        sender.getOutputStream().close();
    }
   
    @Override
    public voidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        new SocketListener(this.handler, this.notificationRunnable).start();
       
        Button send1= (Button)findViewById(R.id.send_1_button);
        send1.setOnClickListener(new OnClickListener() {
           
           @Override
           public void onClick(View v) {
               try {
                    writeSocket("hello");
               } catch (IOException e) {
                   Log.e(getClass().getName(), e.getMessage());
               }
           }
           
        });
    }
}

        

 


Article précédent: Article suivant: