android网络HTTP和TCP

来源:互联网 发布:淘宝客服每天工作内容 编辑:程序博客网 时间:2024/06/06 13:14

制作基于TCP的聊天室

获取访问权限
要访问网络,需要在你的配置文件中获取INTERNET权限

Android客户端

public class MainActivity extends Activity implements OnClickListener {    EditText et;    TextView tv;    OutputStream os;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        et = (EditText) findViewById(R.id.editText1);        tv = (TextView) findViewById(R.id.textView1);        findViewById(R.id.button1).setOnClickListener(this);        findViewById(R.id.button2).setOnClickListener(this);    }    @Override    public void onClick(View v) {        // TODO Auto-generated method stub        if (v.getId() == R.id.button1) {            String info = et.getText().toString();            // 向textView添加内容            tv.append("me:" + info + "\n");            et.setText("");            // 将用户输入的信息发送给服务器            DataOutputStream dos = new DataOutputStream(os);            try {                dos.writeUTF(info);            } catch (IOException e) {                e.printStackTrace();            }        } else if (v.getId() == R.id.button2) {            // 登入聊天室            new AsyncTask<Void, String, Void>() {                @Override                protected Void doInBackground(Void... params) {                    // TODO Auto-generated method stub                    try {                        boolean isRun = true;                        Socket socket = new Socket("192.168.0.103", 8989);                        publishProgress("联网成功", "1");                        os = socket.getOutputStream();                        // 接收服务器数据                        InputStream is = socket.getInputStream();                        DataInputStream dis = new DataInputStream(is);                        while (isRun) {                            // 阻塞                            String info = dis.readUTF();                            publishProgress(info);                        }                    } catch (UnknownHostException e) {                        e.printStackTrace();                    } catch (IOException e) {                        e.printStackTrace();                    }                    return null;                }            protected void onProgressUpdate(String... values) {                    super.onProgressUpdate(values);                    if (values.length == 2) {                        Toast.makeText(MainActivity.this, "联网成",                                Toast.LENGTH_SHORT).show();                    } else {                        tv.append(values[0] + "\n");                    }                }            }.execute();        }    }}

activity_main.

JAVA服务器端public class Test {    public static  ArrayList<Socket> listSocket = new ArrayList<Socket>();    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        boolean isRun = true;        try {            System.out.println(InetAddress.getLocalHost());            ServerSocket server = new ServerSocket(8989);            //客户端的身份编号            int count = 0;            while(isRun){                System.out.println("监听是否有客户端连接...");                Socket socket = server.accept();                count++;                System.out.println("客户端" + count + "已连接");                listSocket.add(socket);                //启动一个新线程                new MyThread(socket, "clinet_"+count).start();            }            server.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}
public class MyThread extends Thread {    Socket socket;    String name;    public MyThread(Socket socket, String name) {        // TODO Auto-generated constructor stub        this.socket = socket;        this.name = name;    }    public void run() {        super.run();        // TODO Auto-generated method stub        boolean isRun = true;        try {            //            InputStream is = socket.getInputStream();            DataInputStream dis = new DataInputStream(is);            while(isRun){                //接收数据                String info = dis.readUTF();                System.out.println(name + ":" + info);                //发送数据 (向所有的客户端发数据,除了自己)                for (int i = 0; i < Test.listSocket.size(); i++) {                    Socket clientSocket = Test.listSocket.get(i);                    if(!clientSocket.equals(this.socket)){                        OutputStream os = clientSocket.getOutputStream();                        DataOutputStream dos = new DataOutputStream(os);                        dos.writeUTF(name + ":" + info);                    }                }            }        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }       }}

基于Http的网络请求

什么是http
超文本传输协议(HyperText Transfer Protocol – HTTP)是一个设计来使客户端和服务器顺利进行通讯的协议。HTTP在客户端和服务器之间以request-response protocol(请求-回复协议)工作。
http请求类型
get请求:从指定的服务器中获取数据
post请求:提交数据给指定的服务器处理

public class MainActivity extends Activity implements OnClickListener {    ImageView iv;    ProgressBar pb;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        iv=(ImageView) findViewById(R.id.imageView1);        pb=(ProgressBar) findViewById(R.id.progressBar1);        findViewById(R.id.button1).setOnClickListener(this);    }    @Override    public void onClick(View v) {        new AsyncTask<String, Void, Bitmap>() {            @Override            protected Bitmap doInBackground(String... params) {                try {                    //创建URL对象                    URL url=new URL(params[0]);                    //打开超链接,得到对象                    HttpURLConnection conn=(HttpURLConnection) url.openConnection();                    //获取字节流                    InputStream is=conn.getInputStream();                    //将字节流的数据读出来生成位图对象                    Bitmap bitmap=BitmapFactory.decodeStream(is);                    return bitmap;                } catch (MalformedURLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                return null;            }            protected void onPostExecute(Bitmap result) {                super.onPostExecute(result);                pb.setVisibility(View.INVISIBLE);                iv.setVisibility(View.VISIBLE);                iv.setImageBitmap(result);            };    }.execute("http://www.nowamagic.net/librarys/images/random/rand_11.jpg");    }}
0 0
原创粉丝点击