Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android版 Sokect服務端和客戶端

Android版 Sokect服務端和客戶端

編輯:關於Android編程

服務端:

主頁xml:



    

    




 

主頁代碼:

 

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

public class MainActivity extends Activity {

    public static ServerSocket serverSocket = null;
    public static TextView mTextView, textView1;
    private String IP = "";
    String buffer = "";
    public static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x11) {
                Bundle bundle = msg.getData();
                mTextView.append("客戶端:" + bundle.getString("msg") + "\n");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        mTextView = (TextView) findViewById(R.id.textsss);
        textView1 = (TextView) findViewById(R.id.textView1);
        mTextView.append("\n");
        IP = getIp();
        textView1.setText("IP addresss:" + IP);
        new Thread() {
            public void run() {
                Bundle bundle = new Bundle();
                bundle.clear();
                OutputStream output;
                String str = "通信成功";
                try {
                    serverSocket = new ServerSocket(30000);
                    while (true) {
                        Message msg = new Message();
                        msg.what = 0x11;
                        try {
                            Socket socket = serverSocket.accept();
                            output = socket.getOutputStream();
//                          ps:注意數據流類型,避免亂碼
//                          output.write(str.getBytes("UTF-8"));//客戶端的數據流為UTF-8
//                          output.write(str.getBytes("gbk"));//客戶端的數據流為gbk
                            output.write(str.getBytes());//服務端和客戶端 數據流類型一致時
                            output.flush();
                            socket.shutdownOutput();
                            BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            String line = null;
                            buffer = "";
                            while ((line = bff.readLine()) != null) {
                                if (!parseJsonMulti(line).equals(""))
                                    line = parseJsonMulti(line);
                                buffer = line + buffer;
                            }
                            bundle.putString("msg", buffer.toString());
                            msg.setData(bundle);
                            mHandler.sendMessage(msg);
                            bff.close();
                            output.close();
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }.start();
    }

    private String parseJsonMulti(final String strResult) {
        String result = "";
        try {
            //解析JSON字符串
            //1.若字符串為JSON數組,則轉為JSON數組,若不是,則轉為JSON對象
            //2.根據JSON裡數據的名稱和類型,來獲取想對應的值
            //JSON裡數據,可能為單個JSON對象,JSON數組,或兩者嵌套的
            //遇到嵌套時,只需對應JSON轉換,再進行獲取

            //獲取字符串並轉為JSONObject
            JSONObject json_data = new JSONObject(strResult);
            // 獲取此次的數據類型。
            String Type = json_data.getString("Type");
            if (Type.equals("單個數據")) {
               /*{\"Type\":\"單個數據\"}*/
                result = Type;
            } else if (Type.equals("多個數據")) {
                /*{\"Type\":\"多個數據\",\"NUM\":\"號碼\"}*/
                String NUM = json_data.getString("NUM");
                result = Type + "  " + NUM;
            } else if (Type.equals("嵌套JSON數組")) {
               /*{\"Type\":\"嵌套JSON數組\",\"Array\":[{\"one\":3},{\"two\":8}]}*/
                //獲取JSON數組
                JSONArray Array = json_data.getJSONArray("Array");
                //獲取JSON數組的JSON對象
//                JSONObject OneObject = (JSONObject) Array.opt(0);
//                JSONObject OneObject = Array.optJSONObject(0);
                //若有很多JSON對象 ,只需把0改為對象所屬下標
                JSONObject OneObject = Array.getJSONObject(0);
                JSONObject TwoObject = Array.getJSONObject(1);
                int one = OneObject.getInt("one");
                int two = TwoObject.getInt("two");
                result = one + "  參數  " + two;
            }

        } catch (final JSONException e) {
            e.printStackTrace();
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 當Server為本機時,獲取本機IP(Wifi或非Wifi均適用)
     */
    public String getIp() {
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        //判斷wifi是否開啟
        if (!wifiManager.isWifiEnabled()) {
            return getLocalIpAddress();
        } else
            return intToIp(wifi_ip(wifiManager));
    }

    //Wifi
    private int wifi_ip(WifiManager wifiManager) {
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        return ipAddress;
    }

    //非Wifi
    public String getLocalIpAddress() {
        try {
            for (Enumeration en = NetworkInterface
                    .getNetworkInterfaces();
                 en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration enumIpAddr = intf
                        .getInetAddresses();
                     enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            return "";
        }
        return "";
    }

    /**
     * 轉化獲取的(16進制)IP地址
     */
    private String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

}


 

客戶端:

主頁xml:

 



    


 

主頁代碼:

 

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Enumeration;

public class MainActivity extends Activity implements OnClickListener {

    Socket socket = null;
    String buffer = "";
    TextView Msg;
    Button send, single, multiple, nested;
    EditText ed_msg;
    /**
     * 發送或接受的字符串
     */
    String io_msg;
    public Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x11) {
                Bundle bundle = msg.getData();
                Msg.append("server:" + bundle.getString("msg") + "\n");
            }
        }
    };

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

        Msg = (TextView) findViewById(R.id.msg);
        send = (Button) findViewById(R.id.send);
        single = (Button) findViewById(R.id.single);
        multiple = (Button) findViewById(R.id.multiple);
        nested = (Button) findViewById(R.id.nested);
        ed_msg = (EditText) findViewById(R.id.ed_msg);

        new SendThread("建立連接", getIp()).start();

        send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String ip = getIp();
                if (!ip.equals("")) {
                    io_msg = ed_msg.getText().toString();
                    Msg.append("client:" + io_msg + "\n");
                    // 向服務器發送和接收信息
                    new SendThread(io_msg, ip).start();
                } else {
                    Toast.makeText(MainActivity.this, "ip地址獲取出錯!", Toast.LENGTH_SHORT).show();
                }
            }
        });

        single.setOnClickListener(this);
        multiple.setOnClickListener(this);
        nested.setOnClickListener(this);
    }

    private void Sendmsg(String json) {
        String ip = getIp();
        if (!ip.equals("")) {
            Msg.append("client:" + json + "\n");
            // 向服務器發送和接收信息
            new SendThread(json, ip).start();
        } else {
            Toast.makeText(MainActivity.this, "ip地址獲取出錯!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.single:
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("Type", "單個數據");
                    Sendmsg(jsonObject.toString());
                } catch (JSONException e) {
                    Toast.makeText(this, "發送失敗!JSON異常", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.multiple:
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("Type", "多個數據");
                    jsonObject.put("NUM", "號碼");
                    Sendmsg(jsonObject.toString());
                } catch (JSONException e) {
                    Toast.makeText(this, "發送失敗!JSON異常", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.nested:
                try {
                    JSONObject OneObject = new JSONObject();
                    OneObject.put("one", "3");

                    JSONObject TwoObject = new JSONObject();
                    TwoObject.put("two", "8");

                    JSONArray jsonArray = new JSONArray();
                    jsonArray.put(OneObject);
                    jsonArray.put(TwoObject);

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("Type", "嵌套JSON數組");
                    jsonObject.put("Array", jsonArray);

                    Sendmsg(jsonObject.toString());
                } catch (JSONException e) {
                    Toast.makeText(this, "發送失敗!JSON異常", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    class SendThread extends Thread {
        public String Ip;
        public String str;

        public SendThread(String _str, String _Ip) {
            str = _str;
            Ip = _Ip;
        }

        @Override
        public void run() {
            // 定義消息
            Message msg = new Message();
            msg.what = 0x11;
            Bundle bundle = new Bundle();
            bundle.clear();
            try {
                // 連接服務器 並設置連接超時為5秒
                socket = new Socket();
                socket.connect(new InetSocketAddress(Ip, 30000), 5000);
                // 獲取輸入輸出流
                OutputStream ou = socket.getOutputStream();
                BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                // 讀取發來服務器信息
                String line = null;
                buffer = "";
                while ((line = bff.readLine()) != null) {
                    buffer = line + buffer;
                }
                // 向服務器發送信息
                // ps:注意數據流類型,避免亂碼
                //ou.write(str.getBytes("UTF-8"));//服務端的數據流為UTF-8
                //ou.write(str.getBytes("gbk"));//服務端的數據流為gbk
//                ou.write(str.getBytes());//服務端和客戶端 數據流類型一致時
                ou.write(str.getBytes());
                ou.flush();
                bundle.putString("msg", buffer.toString());
                msg.setData(bundle);
                // 發送消息 修改UI線程中的組件
                myHandler.sendMessage(msg);
                // 關閉各種輸入輸出流
                bff.close();
                ou.close();
                socket.close();
            } catch (SocketTimeoutException aa) {
                // 連接超時 在UI界面顯示消息
                bundle.putString("msg", "服務器連接失敗!請檢查網絡是否打開");
                msg.setData(bundle);
                // 發送消息 修改UI線程中的組件
                myHandler.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 當Server為本機時,獲取本機IP(Wifi或非Wifi均適用)
     */
    public String getIp() {
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        //判斷wifi是否開啟
        if (!wifiManager.isWifiEnabled()) {
            return getLocalIpAddress();
        } else
            return intToIp(wifi_ip(wifiManager));
    }

    //Wifi
    private int wifi_ip(WifiManager wifiManager) {
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        return ipAddress;
    }

    //非Wifi
    public String getLocalIpAddress() {
        try {
            for (Enumeration en = NetworkInterface
                    .getNetworkInterfaces();
                 en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration enumIpAddr = intf
                        .getInetAddresses();
                     enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            return "";
        }
        return "";
    }

    /**
     * 轉化獲取的(16進制)IP地址
     */
    private String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved