Android学习之路二十:Socket和http

  说到网络开发首先想到的一定是socket变成呢个,在Android系统中也一样。socket(套接字)编程一般分为两部分:服务端(java)和客户端(android)。

  服务器端java代码:

        ServerSocket ss = null;
        Socket s = null;
        DataInputStream din = null;
        DataOutputStream dout = null;
        
        try{
            ss = new ServerSocket(8888);//监听8888端口
        }catch(Exception e){
            e.printStackTrace();
        }
        while(true){
            try{
                s = ss.accept();//等待客户端连接
                din = new DataInputStream(s.getInputStream());
                dout = new DataOutputStream(s.getOutputStream());//得到输入输出流
                String readmsg = din.readUTF();//接收客户端消息
                System.out.println(readmsg);
                dout.writeUTF("Hello Client");//向客户端发送消息
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                //关闭输入输出流和socket
            }
        }

  客户端Android代码:

        Socket s = null;
        DataInputStream din = null;
        DataOutputStream dout = null;
        try{
            s = new Socket();
            //连接服务器超过三秒即连接失败
            s.connect(new InetSocketAddress("127.0.0.1", 8888),3000);
            din = new DataInputStream(s.getInputStream());
            dout = new DataOutputStream(s.getOutputStream());
            //得到输入输出流
            String readmsg = din.readUTF();//接收服务端消息
            dout.writeUTF("Hello Server!");//向服务端发送消息
            s.setSoTimeout(3000);//超过三秒发送失败
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭输入输出流和socket
        }

 

  Android另外一种网络编程技术为HTPP协议,其中最简单的应用就是通过URL获取网络资源。使用HTTP协议需要添加网络权限android.permission.INTERNET。

  代码:

        URLConnection ucon = null;
        BufferedInputStream bufin = null;
        ByteArrayBuffer bab = null;
        
        try{
            URL myURL = new URL("http://www.baidu.com/");//初始化URL
            ucon = myURL.openConnection();//打开连接
            bufin = new BufferedInputStream(ucon.getInputStream());//得到输入流
            int current = 0;
            bab = new ByteArrayBuffer(1000);
            while((current = bufin.read())!=-1){
                bab.append((char)current);//将收到的信息添加到ByteArrayBuffer中
            }
            String res = EncodingUtils.getString(bab.toByteArray(), "UTF-8");
        }catch(MalformedURLException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{
                if(bufin!=null){
                    bufin.close();
                    bufin = null;
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }

 

posted @ 2013-02-21 15:45  洒洒  阅读(1746)  评论(0编辑  收藏  举报