Android学习之路二十:Socket和http
发布日期:2021-09-08 01:44:40 浏览次数:37 分类:技术文章

本文共 2578 字,大约阅读时间需要 8 分钟。

  说到网络开发首先想到的一定是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();            }        }

 

转载地址:https://blog.csdn.net/weixin_34310369/article/details/85540903 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:设置相关---blogs-set
下一篇:setsockopt中参数之SO_REUSEADDR的意义(转)

发表评论

最新留言

不错!
[***.144.177.141]2024年03月30日 03时27分46秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章