关闭

Android版 Sokect服务端和客户端

标签: androidSocketjson发送与接收json解析
491人阅读 评论(0) 收藏 举报
分类:

服务端:

主页xml:

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

    <TextView
        android:id="@+id/textsss"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:text="     连接情况"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="35dp"
        android:gravity="center"
        android:text="IP地址"
        android:textSize="18sp" />

</RelativeLayout>


主页代码:

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<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces();
                 en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> 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:

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

    <EditText
        android:id="@+id/ed_msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="给服务器发送信息" />

    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送" />

    <TextView
        android:id="@+id/msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/single"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="单个数据" />

    <Button
        android:id="@+id/multiple"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="多个数据  " />

    <Button
        android:id="@+id/nested"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="嵌套JSON数组" />

</LinearLayout>


主页代码:

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<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces();
                 en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> 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,已全部贴出!已上传Demo,需要的请下载!参考博客:http://blog.csdn.net/u014388322/article/details/43016653

0
0

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2896次
    • 积分:107
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:1篇
    • 译文:0篇
    • 评论:1条
    最新评论