欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

Android自学历程—Socket的简单使用

来源: 开发者 投稿于  被查看 16355 次 评论:137

Android自学历程—Socket的简单使用


activity_main.java
 
 
 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical"
 6     tools:context=".MainActivity">
 7 
 8     <EditText
 9         android:id="@+id/editText"
10         android:layout_width="match_parent"
11         android:layout_height="wrap_content"
12         android:hint="请输入要发送的内容"/>
13     
14     <Button
15         android:id="@+id/button01"
16         android:layout_width="match_parent"
17         android:layout_height="wrap_content"
18         android:text="连接"/>
19 
20     <Button
21         android:id="@+id/button02"
22         android:layout_width="match_parent"
23         android:layout_height="wrap_content"
24         android:text="发送"/>
25 
26     <ScrollView
27         android:layout_width="match_parent"
28         android:layout_height="wrap_content"
29         android:scrollbars="vertical"
30         android:fadingEdge="vertical">
31         <TextView
32             android:id="@+id/textView"
33             android:layout_width="match_parent"
34             android:layout_height="wrap_content"
35             android:text="输出信息:"/>
36     </ScrollView>
37 
38 </LinearLayout>
 

 

 
 
 
界面很是简单。
 
 
 
下面我们需要一个服务器,和一个客户端。服务器,我用的是Eclipse写的Java的服务器;客户端,我用的是Android Studio写的。
 
 
package com.ryan.socketdemo01;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

/**
 * 本实例功能: 客户端发送数据至客户端(动态输出数据)
 *
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button button01 = null;
    private Button button02 = null;
    private EditText editText = null;
    private TextView textView = null;

    private static Socket ClientSocket = null;
    private byte[] msgBuffer = null;
    Handler handler = new Handler();


    private void initView() {
        button01 = (Button) findViewById(R.id.button01);
        button02 = (Button) findViewById(R.id.button02);
        editText = (EditText) findViewById(R.id.editText);
        textView = (TextView) findViewById(R.id.textView);

        button01.setOnClickListener(this);
        button02.setOnClickListener(this);

        button01.setEnabled(true);
        button02.setEnabled(false);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button01:
                // TODO: 15-9-4 socket连接线程
                connectThread();
                break;
            case R.id.button02:
                // TODO: 15-9-4 发送数据线程
                sendMsgThread();
                break;
        }
    }

    private void sendMsgThread() {

        final String text = editText.getText().toString();
        try {
            msgBuffer = text.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OutputStream outputStream;
                    //Socket输出流
                    outputStream = ClientSocket.getOutputStream();

                    outputStream.write(msgBuffer);
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        textView.append("发送成功:"+text+"\n");
                    }
                });
            }
        }).start();
    }

    private void connectThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ClientSocket = new Socket("10.0.2.2",9001);
                    if (ClientSocket.isConnected()){
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                textView.append("连接成功!"+"\n");
                                button01.setEnabled(false);
                                button02.setEnabled(true);
                            }
                        });
                    }else {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                textView.append("连接失败!"+"\n");
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }







    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

 

 
 
 
 
这里我的线程使用方式是:
 
 
new Thread (new Runnable) {
      @Override
      public void run() {
      }  
}    
 

 

 
 
 网上有人说这个方式很LOW,而且不好,但现在我只会这个,就连asynctask也还在学习中。
 
 
 
 
 
还有一点,子线程更新主UI的方法:
 
我使用的是 Handler.post();  同样十分简单的使用方法。
 
Handler handler = new Handler(); 

handler.post(new Runnable() {
                    @Override
                    public void run() {
                        textView.append("发送成功:"+text+"\n");
                    }
                });
 

 

 
 
关于几种子线程更新主UI的方法,我以后会再写一篇博客。我现在已经知道了不下4中方法,还没实地操作。
 
 

用户评论