Android笔记:Socket

client.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="接收到的信息" />

    <TextView
        android:id="@+id/tv1"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_weight="0.25"
        android:text="" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="请输入发送内容" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
         <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送" />
          <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="设置" />
        
    </LinearLayout>

  

</LinearLayout>

client.java

package com.example.testsocket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Client extends Activity {
    public String Ipstr = "10.0.0.113";
    public int port = 13000;
    private String TAG = "===Client===";
    private TextView tv1 = null;
    private Runnable mRunable = null;
    private Runnable mRunablesend = null;
    Handler mhandler;
    boolean isRun = true;
    EditText edtsendms;
    Button btnsend;
    private String sendstr = "";
    SharedPreferences sp;
    Button btnSetting;
    private Context ctx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.client);
        tv1 = (TextView) findViewById(R.id.tv1);
        btnsend = (Button) findViewById(R.id.button1);
        ctx = Client.this;
        edtsendms = (EditText) findViewById(R.id.editText1);
        initdate();
        btnSetting = (Button) findViewById(R.id.button2);
        btnsend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 发送数据
                sendstr = edtsendms.getText().toString().trim();
                new Thread(mRunablesend).start();

            }
        });
        btnSetting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 跳转到设置界面
                Intent intent = new Intent();
                intent.setClass(Client.this, Setting.class);
                Log.i(TAG, "开始打开新窗体");
                ctx.startActivity(intent);// 打开新界面

            }
        });
        mRunable = new Runnable() {
            public void run() {
                Log.i(TAG, "进入线程");
                while (isRun) {
                    try {
                        Socket socket = new Socket(Ipstr, port);
                        Log.i(TAG, "2.接收数据");
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(socket.getInputStream()));
                        String line = in.readLine();
                        Log.i(TAG, "获取到下发数据" + line);
                        Log.i(TAG, "3.发送至mhandler");
                        Message msg = mhandler.obtainMessage();
                        msg.obj = line;
                        mhandler.sendMessage(msg);
                        Log.i(TAG, "4.关闭连接");
                        in.close();
                        socket.close();
                    } catch (Exception e) {
                        Log.i(TAG, "出现异常2");
                        e.printStackTrace();
                    }
                }
            }
        };
        mhandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                try {
                    Log.i(TAG, "mhandler接收到msg=" + msg.what);
                    // clientShow.setText(msg.what);
                    if (msg.obj != null) {
                        String s = msg.obj.toString();
                        if (s.trim().length() > 0) {
                            Log.i(TAG, "mhandler接收到obj=" + s);
                            Log.i(TAG, "开始更新UI");
                            tv1.setText((String) msg.obj);
                            Log.i(TAG, "更新UI完毕");
                        } else {
                            Log.i(TAG, "没有数据返回不更新");
                        }
                    }
                } catch (Exception ee) {
                    Log.i(TAG, "加载过程出现异常");
                    ee.printStackTrace();
                }
            }
        };
        mRunablesend = new Runnable() {
            public void run() {
                Send();
            }
        };

        Log.i(TAG, "启动线程");
        new Thread(mRunable).start();// 启动线程
    }

    public void Send() {
        try {
            Log.i(TAG, "准备数据:" + sendstr);
            Socket socket = new Socket(Ipstr, port);
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
            out.println(sendstr);
            out.flush();
            out.close();
            Log.i(TAG, "发送成功");
            socket.close();
        } catch (Exception e) {
            Log.i(TAG, "发送错误");
            e.printStackTrace();
        } finally {

        }
    }
    
    public void initdate()
    {
        sp = this.getSharedPreferences("SP", MODE_PRIVATE);
        Ipstr = sp.getString("ipstr", "10.0.0.113");
        port = Integer.parseInt(sp.getString("port", "13000"));
        Log.i(TAG, "获取到ip端口:" + Ipstr + ";" + port);
    }

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

    @Override
    protected void onStart() {
        super.onStart();
        Log.e(TAG, "start onStart~~~");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e(TAG, "start onRestart~~~");
        initdate();
        Log.e(TAG, "start get ip  and port~~~");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "start onResume~~~");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "start onPause~~~");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "start onStop~~~");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "start onDestroy~~~");
    }

}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。