LocalSocket/LocalServerSocket

前言

  本章內容android.net.LocalSocket章節,版本爲Android 4.0 r1,翻譯來自:"水中影",歡迎訪問他的博客:"http://www.cnblogs.com/gosunriver/",再次感謝"水中影" !期待你一起參與翻譯Android的相關資料,聯繫我[email protected]

聲明

  歡迎轉載,但請保留文章原始出處:) 

    博客園:http://www.cnblogs.com/

    Android中文翻譯組:http://androidbox.sinaapp.com/

LocalSocket

譯者署名:水中影

譯者鏈接:http://www.cnblogs.com/gosunriver/

 版本: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)

activity_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 String SOCKET_ADDRESS = "your.local.socket.address";
   
   // background threads use this Handler to post messages to
    // the main application thread
    private final Handler handler = new Handler();
   
    public class NotificationRunnable implements Runnable {
        private String message = null;
        
        public void run() {
            if (message != null && message.length() > 0) {
                showNotification(message);
            }
        }
       
        /**
        * @param message the message to set
        */
        public void setMessage(String message) {
            this.message = message;
        }
    }
   
    // post this to the Handler when the background thread notifies
    private final NotificationRunnable notificationRunnable = new NotificationRunnable();
   
    public void showNotification(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
   
    class SocketListener extends Thread {
        private Handler handler = null;
        private NotificationRunnable runnable = null;
       
        public SocketListener(Handler handler, NotificationRunnable runnable) {
            this.handler = handler;
            this.runnable = runnable;
            this.handler.post(this.runnable);
        }
       
        /**
        * Show UI notification.
        * @param message
        */
        private void showMessage(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) {
                    LocalSocket receiver = server.accept();
                    if (receiver != null) {
                        InputStream input = receiver.getInputStream();
                       
                        // simply for java.util.ArrayList
                        int readed = 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 void writeSocket(String message) throws IOException {
        LocalSocket sender = new LocalSocket();
        sender.connect(new LocalSocketAddress(SOCKET_ADDRESS));
        sender.getOutputStream().write(message.getBytes());
        sender.getOutputStream().close();
    }
   
    @Override
    public void onCreate(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());
                }
            }
           
       });
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章