android --- LocalSocket

来源:互联网 发布:淘宝老板旗舰店 编辑:程序博客网 时间:2024/06/05 00:27

前言

  本章内容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 FileDescriptorgetFileDescriptor ()

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

返回值

文件描述符或空​

 

public InputStream getInputStream ()

         获取输入流。

         ​返回值​

input stream对象

         异常

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

public LocalSocketAddressgetLocalSocketAddress ()

若存在则返回绑定的socket

         返回值

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

 

public OutputStreamgetOutputStream ()

获取输出流

         返回值

输出流

         异常

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

 

public Credentials getPeerCredentials ()

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

返回值

非空;认证信息

         异常

IOException

 

public int getReceiveBufferSize ()

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

         异常

IOException

 

public LocalSocketAddressgetRemoteSocketAddress ()

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

 

public int getSendBufferSize ()

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

         异常

IOException

 

public int getSoTimeout ()

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

         异常

IOException

 

public synchronized booleanisBound ()

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

 

public boolean isClosed ()

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

 

public synchronized booleanisConnected ()

(译者注:是否已连接)

 

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

   <Buttonandroid: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
*
*/
publicclassDemoActivityextendsActivity{
   
    publicstaticString SOCKET_ADDRESS="your.local.socket.address";
   
   // background threads use this Handler to post messages to
    // the main application thread
    privatefinalHandler handler=newHandler();
   
    publicclassNotificationRunnableimplementsRunnable{
       privateString message=null;
        
       publicvoid run(){
           if(message!=null&& message.length()> 0){
                showNotification(message);
           }
       }
       
       /**
        * @param message the message to set
        */
       publicvoid setMessage(String message){
           this.message= message;
       }
    }
   
    // post this to the Handler when the background thread notifies
    privatefinalNotificationRunnable notificationRunnable=newNotificationRunnable();
   
    publicvoid showNotification(String message){
       Toast.makeText(this, message,Toast.LENGTH_SHORT).show();
    }
   
    classSocketListenerextendsThread{
       privateHandler handler=null;
       privateNotificationRunnable runnable=null;
       
       publicSocketListener(Handler handler,NotificationRunnable runnable){
           this.handler= handler;
           this.runnable= runnable;
           this.handler.post(this.runnable);
       }
       
       /**
        * Show UI notification.
        * @param message
        */
       privatevoid showMessage(String message){
           this.runnable.setMessage(message);
           this.handler.post(this.runnable);
       }
       
       @Override
       publicvoid run(){
           //showMessage("DEMO: SocketListener started!");
           try{
               LocalServerSocket server=newLocalServerSocket(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=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(IOException e){
               Log.e(getClass().getName(), e.getMessage());
           }
       }
    }
   
    publicstaticvoid writeSocket(String message)throwsIOException{
       LocalSocket sender=newLocalSocket();
        sender.connect(newLocalSocketAddress(SOCKET_ADDRESS));
        sender.getOutputStream().write(message.getBytes());
        sender.getOutputStream().close();
    }
   
    @Override
    publicvoid onCreate(Bundle savedInstanceState){
       super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
       newSocketListener(this.handler,this.notificationRunnable).start();
       
       Button send1=(Button)findViewById(R.id.send_1_button);
        send1.setOnClickListener(newOnClickListener(){
           
           @Override
            publicvoid onClick(View v){
               try{
                    writeSocket("hello");
               }catch(IOException e){
                   Log.e(getClass().getName(), e.getMessage());
               }
           }
           
       });
    }
}


原创粉丝点击