Android中文API(137) —— LocalSocket

weixin_34104341發表於2020-04-07

 

前言

  本章內容android.net.LocalSocket章節,版本為Android 4.0 r1,翻譯來自:"水中影",歡迎訪問他的部落格:"http://www.cnblogs.com/gosunriver/",再次感謝"水中影" !期待你一起參與翻譯Android的相關資料,聯絡我over140@gmail.com。

 

宣告

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

    部落格園: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)

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());
                }
            }
           
       });
    }
}

        

轉載於:https://www.cnblogs.com/over140/archive/2011/11/22/2258372.html

相關文章