使用Joson的格式字符串在Socket中通讯时数据格式的转换

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weizhiai12/article/details/7080147

最近在测试通讯模块时,发现新增的Android平台发送过来的数据,服务器端总是收不到,后来发现java中数据类型有些和C#中的不一样,比如C#中byte对应范围是0~255,而Java中则对应的是-128~127,因此直接按照通讯协议传序列化的二进制流总是出现问题。考虑到这一点在Android那一端才用Joson序列化发送到服务端,而在服务端对接收到的数据进行反序列化后转化为对象。同时在服务端进行发送数据时,转换为Joson格式后,序列化为二进制流发生给Android端。

废话不多说了,上代码:

//Joson格式的二进制流转换为对象

 public static T JosonDeSerializer<T>(byte[] buffer, int length)
        {
            try
            {
                string mTextReceived = Encoding.UTF8.GetString(buffer, 0, length);

                //将获取到的Joson格式字符串转换为数据包类
                SocketDataPack sdp = GetSocketDataPackFromString(mTextReceived);
                MemoryStream stream = new MemoryStream();
                BinaryFormatter formatter = new BinaryFormatter();

                //将数据包类序列化
                formatter.Serialize(stream, sdp);
                stream.Position = 0;
                stream.Flush();

                //转换为对象
                object obj = formatter.Deserialize(stream);
                if (obj == null)
                {
                    return default(T);
                }
                return (T)obj;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //对象转换为Joson格式二进制流
        public static byte[] JosonSerializer(object input)
        {
            try
            {
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                string strSocketDataPack = jsonSerializer.Serialize(input);
                byte[] buffer = Encoding.UTF8.GetBytes(strSocketDataPack);
                return buffer;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// <summary>
        /// 将Json格式的字符串转换为指定的数据包类
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private static SocketDataPack GetSocketDataPackFromString(string context)
        {
            try
            {
                SocketDataPack sdp = new SocketDataPack();
                context = context.Replace("{", "").Replace("[", "").Replace("]", "").Replace("}", "").Replace("\"", "").Replace("\0","");
                String[] str = context.Split(',');
                for (int i = 0; i < str.Length; i++)
                {
                    String[] str2 = str[i].Split(':');
                    switch (str2[0])
                    {
                        case "Length":
                            sdp.Length = Convert.ToInt16(str2[1]);
                            break;
                        case "Head":
                            sdp.Head = Convert.ToByte(str2[1]);
                            break;
                      //中间的数据包类的类型省略
                        。。。
                        case "Status":
                            sdp.Status = Convert.ToByte(str2[1]);
                            break;
                        case "Tail":
                            sdp.Tail = Convert.ToByte(Convert.ToInt16(str2[1]));
                            break;
                    }
                }
                return sdp;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

展开阅读全文

socket通讯时出现大包

05-21

正常情况下包的长度是9~500左右的长度的,后台基本不会发来大包,后台发送日志也是正常的,但是android 端就经常出现这个情况,要怎么处理,看了网上的文章,说是粘包,也提到一些思路,我这边是用自定义协议的,结合我的项目用代码实现思路也不清晰,希望大神路过指点一二。rnrn[color=#FF0000]下面是错误信息[/color]rn[code=java]java.lang.OutOfMemoryError: Failed to allocate a 842019138 byte allocation with 16777216 free bytes and 481MB until OOMrn at fuhao.com.app.net.TcpSocketZ$ReceiveThread.run(TcpSocketZ.java:255)[/code]rnrn[color=#FF0000]下面是代码:代码有点乱,还没做整理,这个是TcpSocket实现Runnable的run方法:[/color]rn[code=java] @Overridern        public synchronized void run() rn            try rn                int packetLen = 0;rn                while (isRunning) rn                    if (!isConnected) rn                        mSocket = new Socket(HostIP, Port);rn                        mSocket.setSendBufferSize(1024);rn                        mSocket.setReceiveBufferSize(1024);rn                        mSocket.setTcpNoDelay(true);rn                        mSocket.setKeepAlive(true);rn                        mDos = new DataOutputStream(mSocket.getOutputStream());rn                        mDis = new DataInputStream(mSocket.getInputStream());rn                        handshark();rn                        isConnected = true;rn                        startHeartBeat();rn                     else rn                        if (mDis.available() >= 4) rn                            packetLen = mDis.readInt();rn                            L.e("TcpSocketZ", "-----packetLen------" + packetLen);rn                            if (packetLen > 0) rn                                byte iszlib = mDis.readByte();rn                                if (iszlib == (byte) 1) rn                                    try rn                                        byte[] inputData = new byte[packetLen - 1];rn                                        utils.readData(mDis, inputData, 0, packetLen - 1);rn                                        byte[] result = CompressUtil.decompress(inputData);rn                                        byteReader br = new byteReader(result);rn                                        int alias = br.readInt();rn                                        L.e("TcpSocketZ", "recv packet zlib ------" + String.valueOf(alias));rn                                        baseProto obj = ClassFactory.getProtoObject(alias);rn                                        if (obj != null) rn                                            obj.parseFrom(br);rn                                            EventBus.getDefault().post(new ResEvent(obj));rn                                        rn                                     catch (DataFormatException e) rn                                        e.printStackTrace();rn                                    rn                                 else rn                                    byte[] inputData = new byte[packetLen - 1];rn                                    utils.readData(mDis, inputData, 0, packetLen - 1);rn                                    byteReader br = new byteReader(inputData);rn                                    int alias = br.readInt();rn                                    L.e("TcpSocketZ", "packet alias------" + String.valueOf(alias));rn                                    if (alias == 20002) rn                                        backTime = 0;rn                                    rn                                    baseProto obj = ClassFactory.getProtoObject(alias);rn                                    if (obj != null) rn                                        obj.parseFrom(br);rn                                        EventBus.getDefault().post(new ResEvent(obj));rn                                    rn                                rn                            rn                        rn                    rn                rn                mDos.close();rn                mDis.close();rn                if (mSocket != null) rn                    mSocket.close();rn                    mSocket = null;rn                rn                this.isRunning = false;rn                reconnect();rn             catch (EOFException e) rn                this.isConnected = false;rn                try rn                    mDos.close();rn                    mDis.close();rn                    if (mSocket != null) rn                        mSocket.close();rn                        mSocket = null;rn                    rn                 catch (IOException e1) rn                    e1.printStackTrace();rn                rn                reconnect();rn                e.printStackTrace();rn             catch (SocketException e) rn                e.printStackTrace();rn                this.isConnected = false;rn                try rn                    mDos.close();rn                    mDis.close();rn                    if (mSocket != null) rn                        mSocket.close();rn                        mSocket = null;rn                    rn                 catch (IOException e1) rn                    e1.printStackTrace();rn                rn                reconnect();rn                e.printStackTrace();rn             catch (UnknownHostException e) rn                e.printStackTrace();rn                this.isConnected = false;rn                try rn                    mDos.close();rn                    mDis.close();rn                    if (mSocket != null) rn                        mSocket.close();rn                        mSocket = null;rn                    rn                 catch (IOException e1) rn                    e1.printStackTrace();rn                rn                reconnect();rn                e.printStackTrace();rn             catch (IOException e) rn                this.isConnected = false;rn                try rn                    mDos.close();rn                    mDis.close();rn                    if (mSocket != null) rn                        mSocket.close();rn                        mSocket = null;rn                    rn                 catch (IOException e1) rn                    e1.printStackTrace();rn                rn                reconnect();rn                e.printStackTrace();rn rn            rn        [/code]rnrn[color=#FF0000]错误的是出现在上面代码的第40行[/color] 论坛

没有更多推荐了,返回首页