安卓的socket连接

来源:互联网 发布:mac橙色系口红 推荐 编辑:程序博客网 时间:2024/06/16 22:43

安卓的socket连接
这里主要涉及socket连接是不可能放在主线程里的,不过你做server还是做client,另外接受到的数据不要使用char[]的tostring来转,因为样涉及字符编码格式,当然二进制数据不存在这样的问题
package com.example.zmy.sockettest;import android.app.AlertDialog;import android.content.DialogInterface;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.Socket;public class MainActivity extends ActionBarActivity {    private static final String HOST = "192.168.1.116";    private static final int PORT = 8999;    private Socket socket = null;    private BufferedReader in = null;    private PrintWriter out = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Thread workThread = new Thread(new Service());        workThread.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);    }    public void ShowDialog(String msg) {        new AlertDialog.Builder(this).setTitle("notification").setMessage(msg)                .setPositiveButton("ok", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                    }                }).show();    }    class Service implements Runnable {        private String content = null;        @Override        public void run() {            try {                socket = new Socket(HOST, PORT);                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));                out = new PrintWriter(socket.getOutputStream());//new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);            }            catch (IOException ex)            {                Log.i("info", ex.getMessage());                ex.printStackTrace();                ShowDialog("login exception" + ex.getMessage());            }            while(true) {                if(socket.isConnected())                {                    Log.i("info", "send first .................................");                    out.print("Android first");                    out.flush();                    break;                }            }            Log.i("info", "enter receive loop .................................");            try {                while (true) {                    if (!socket.isClosed()) {                        if (socket.isConnected()) {                            if (!socket.isInputShutdown()) {                                char[] tmpBuff = new char[256];                                if (/*(content = in.readLine())!= null*/ in.read(tmpBuff) > 0 ) {                                    //content += "\n";                                    //mHandler.sendMessage(mHandler.obtainMessage());                                    content = new String(tmpBuff) ;                                    out.print("Android message:" + content );                                    //out.print("Android message:" + tmpBuff[0] + "," + tmpBuff[1] + "," + tmpBuff[2] + "," + tmpBuff[3] + "," + tmpBuff[4]);                                    out.flush();                                    Thread.sleep(1000);                                }                            }                        }                    }                }            } catch (Exception e) {                e.printStackTrace();            }        }    }}




0 1
原创粉丝点击