unity3d socket编程案例

转自:http://blog.csdn.net/zhou_xw6511/article/details/8479545


这几天研究了下Socket交互。
    通过网上的资料做了有关Socket的第一个Demo,虽然不是很成熟,但个人感觉已经相对比较完整了。各类型数据的传输接受都有,其中也做了float类型的(因为我感觉做Unity应该用的着)。
    功能方面,为了测试多用户交互,我在Demo上开启了4个Socket 4个线程接受数据。实现了服务端通知用户进入 离开功能。
    真机上,需要加上字库,要不无法显示中文。
    
    工程目录:

 

    下面上代码:

客户端代码:

[csharp]  view plain copy
  1. using UnityEngine;  
  2. using System;  
  3. using System.Collections;  
  4. using LSocket.Net;  
  5. using LSocket.Type;  
  6. using LSocket.cmd;  
  7.   
  8.    public class SocketDemo : MonoBehaviour  
  9.    {  
  10.        public UnitySocket[] socket;  
  11.        public String[] textAreaString;  
  12.        public String[] textFieldString;  
  13.        public GUISkin mySkin;  
  14.        // Use this for initialization   
  15.        void Start()  
  16.        {  
  17.            socket = new UnitySocket[4];  
  18.            textAreaString = new String[12];  
  19.            for (int i = 0; i < 12; i++)  
  20.            {  
  21.                textAreaString[i] = "";  
  22.            }  
  23.            textFieldString = new String[4];  
  24.            for(int i=0;i<4;i++){  
  25.                textFieldString[i] = "";  
  26.            }  
  27.        }  
  28.   
  29.        // Update is called once per frame   
  30.        void Update()  
  31.        {  
  32.   
  33.        }  
  34.   
  35.        void OnGUI()  
  36.        {  
  37.            GUI.skin = mySkin;  
  38.            for (int i = 0; i < 4; i++)  
  39.            {  
  40.                String s = textAreaString[i * 3] + "\n" + textAreaString[i * 3 + 1] + "\n" + textAreaString[i * 3 + 2];  
  41.                GUI.TextArea(new Rect(i % 2 * Screen.width / 2, i / 2 * (Screen.height / 2) + 50, 100, 60), s);  
  42.                textFieldString[i] = GUI.TextField(new Rect(i % 2 * Screen.width / 2+50, i / 2 * (Screen.height / 2), 100, 20), textFieldString[i]);  
  43.                if (GUI.Button(new Rect(i % 2 * Screen.width / 2, i / 2 * (Screen.height / 2), 40, 20), "连接"))  
  44.                {  
  45.                    socket[i] = null;  
  46.                    socket[i] = new UnitySocket();  
  47.                    socket[i].SocketConnection("192.168.0.8", 10000, this, i);  
  48.                    socket[i].DoLogin(textFieldString[i]);  
  49.                }  
  50.                else if (GUI.Button(new Rect(i % 2 * Screen.width / 2, i / 2 *( Screen.height / 2) + 25, 40, 20), "关闭"))  
  51.                {  
  52.                    if (socket[i] != null)  
  53.                    {  
  54.                        socket[i].close();  
  55.                        socket[i] = null;  
  56.                    }  
  57.                }  
  58.            }  
  59.   
  60.            if (GUI.Button(new Rect(Screen.width - 60, Screen.height - 30, 60, 30), "退出")) {  
  61.                Application.Quit();  
  62.            }  
  63.   
  64.        }  
  65.    }  



 

[csharp]  view plain copy
  1. namespace LSocket.Net   
  2. /** 
  3.  *  
  4.  * @author feng侠,qq:313785443 
  5.  * @date 2010-12-23 
  6.  * 
  7.  */  
  8.   
  9.     // 描   述:封装c# socket数据传输协议    
  10.     using UnityEngine;   
  11.     using System;   
  12.     using System.Net.Sockets;   
  13.     using System.Net;   
  14.     using System.Collections;   
  15.     using System.Text;  
  16.     using System.Threading;  
  17.     using LSocket.Type;   
  18.     using LSocket.cmd;  
  19.   
  20.   
  21.     class SocketThread  
  22.     {  
  23.   
  24.         UnitySocket socket;  
  25.         SocketDemo demo;  
  26.         int idx;  
  27.   
  28.         public SocketThread(UnitySocket socket, SocketDemo demo, int idx)  
  29.         {  
  30.             this.socket = socket;  
  31.             this.demo = demo;  
  32.             this.idx = idx;  
  33.         }  
  34.   
  35.         public void run()  
  36.         {  
  37.             while (true)  
  38.             {  
  39.                 try  
  40.                 {  
  41.                     String s = socket.ReceiveString();  
  42.                     demo.textAreaString[idx * 3] = demo.textAreaString[idx * 3 + 1];  
  43.                     demo.textAreaString[idx * 3 + 1] = demo.textAreaString[idx * 3 + 2];  
  44.                     demo.textAreaString[idx * 3 + 2] = s;  
  45.                     MonoBehaviour.print(s + " " + idx);  
  46.                 }  
  47.                 catch (Exception e)  
  48.                 {  
  49.                     MonoBehaviour.print(e.ToString());  
  50.                     socket.t.Abort();  
  51.                 }  
  52.             }  
  53.         }  
  54.   
  55.     }  
  56.   
  57.     public class UnitySocket   
  58.     {   
  59.         public Socket mSocket = null;  
  60.         public Thread t=null;  
  61.         private SocketThread st=null;  
  62.         public SocketDemo demo=null;  
  63.   
  64.         public UnitySocket()   
  65.         {   
  66.                
  67.         }   
  68.         public void SocketConnection(string LocalIP, int LocalPort,SocketDemo demo,int idx)   
  69.         {  
  70.             this.demo=demo;  
  71.             mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);   
  72.             try   
  73.             {   
  74.                    
  75.                 IPAddress ip = IPAddress.Parse(LocalIP);   
  76.                 IPEndPoint ipe = new IPEndPoint(ip, LocalPort);   
  77.                 mSocket.Connect(ipe);  
  78.                 st =new SocketThread(this, demo, idx);  
  79.                 t = new Thread(new ThreadStart(st.run));  
  80.                 t.Start();  
  81.             }   
  82.             catch (Exception e)   
  83.             {  
  84.                 MonoBehaviour.print(e.ToString());  
  85.             }   
  86.         }  
  87.           
  88.         public void close(){  
  89.             mSocket.Close(0);  
  90.             mSocket=null;  
  91.         }  
  92.   
  93.         public void DoLogin(String userName){  
  94.             try  
  95.             {  
  96.                 Send(CommandID.LOGIN);  
  97.                 Send(userName);  
  98.             }catch(Exception e){  
  99.                 MonoBehaviour.print(e.ToString());  
  100.             }  
  101.         }  
  102.   
  103.   
  104.         public void Send(float data){  
  105.             byte[] longth = TypeConvert.getBytes(data, true);  
  106.             mSocket.Send(longth);  
  107.         }  
  108.   
  109.         public float ReceiveFloat()  
  110.         {  
  111.             byte[] recvBytes = new byte[4];  
  112.             mSocket.Receive(recvBytes, 4, 0);//从服务器端接受返回信息    
  113.             float data = TypeConvert.getFloat(recvBytes, true);  
  114.             return data;  
  115.         }   
  116.   
  117.         public void Send(short data)   
  118.         {   
  119.             byte[] longth=TypeConvert.getBytes(data,true);   
  120.             mSocket.Send(longth);  
  121.         }   
  122.            
  123.         public void Send(long data)   
  124.         {   
  125.             byte[] longth=TypeConvert.getBytes(data,true);   
  126.             mSocket.Send(longth);   
  127.         }   
  128.            
  129.         public void Send(int data)   
  130.         {   
  131.             byte[] longth=TypeConvert.getBytes(data,true);   
  132.             mSocket.Send(longth);   
  133.                
  134.         }   
  135.            
  136.         public void Send(string data)   
  137.         {   
  138.             byte[] longth=Encoding.UTF8.GetBytes(data);  
  139.             Send(longth.Length);  
  140.             mSocket.Send(longth);   
  141.                
  142.         }   
  143.            
  144.         public short ReceiveShort()   
  145.         {   
  146.              byte[] recvBytes = new byte[2];   
  147.              mSocket.Receive(recvBytes,2,0);//从服务器端接受返回信息    
  148.              short data=TypeConvert.getShort(recvBytes,true);   
  149.              return data;   
  150.         }   
  151.            
  152.         public int ReceiveInt()   
  153.         {   
  154.              byte[] recvBytes = new byte[4];   
  155.              mSocket.Receive(recvBytes,4,0);//从服务器端接受返回信息    
  156.              int data=TypeConvert.getInt(recvBytes,true);   
  157.              return data;   
  158.         }   
  159.            
  160.         public long ReceiveLong()   
  161.         {   
  162.              byte[] recvBytes = new byte[8];   
  163.              mSocket.Receive(recvBytes,8,0);//从服务器端接受返回信息    
  164.              long data=TypeConvert.getLong(recvBytes,true);   
  165.              return data;   
  166.         }   
  167.            
  168.         public String ReceiveString()   
  169.         {   
  170.              int length = ReceiveInt();  
  171.              MonoBehaviour.print("Stringlen="+length);  
  172.              byte[] recvBytes = new byte[length];   
  173.              mSocket.Receive(recvBytes,length,0);//从服务器端接受返回信息    
  174.              String data = Encoding.UTF8.GetString(recvBytes);   
  175.              return data;   
  176.         }   
  177.            
  178.            
  179.     }  
  180. }   


 

[csharp]  view plain copy
  1. namespace LSocket.Type  
  2. {  
  3.     using UnityEngine;  
  4.     using System.Collections;  
  5.   
  6.     public class TypeConvert  
  7.     {  
  8.   
  9.         public TypeConvert()  
  10.         {  
  11.         }  
  12.   
  13.         public  static byte[] getBytes(float s,bool asc){  
  14.             int buf = (int)(s * 100);  
  15.             return getBytes(buf,asc);  
  16.         }  
  17.       
  18.          public static float getFloat(byte[] buf,bool asc){  
  19.             int i=getInt(buf,asc);  
  20.             float s=(float)i;  
  21.             return s/100;  
  22.         }  
  23.   
  24.         public static byte[] getBytes(short s, bool asc)  
  25.         {  
  26.             byte[] buf = new byte[2];  
  27.             if (asc)  
  28.             {  
  29.                 for (int i = buf.Length - 1; i >= 0; i--)  
  30.                 {  
  31.                     buf[i] = (byte)(s & 0x00ff);  
  32.                     s >>= 8;  
  33.                 }  
  34.             }  
  35.             else  
  36.             {  
  37.                 for (int i = 0; i < buf.Length; i++)  
  38.                 {  
  39.   
  40.                     buf[i] = (byte)(s & 0x00ff);  
  41.                     s >>= 8;  
  42.                 }  
  43.             }  
  44.             return buf;  
  45.         }  
  46.         public static byte[] getBytes(int s, bool asc)  
  47.         {  
  48.             byte[] buf = new byte[4];  
  49.             if (asc)  
  50.                 for (int i = buf.Length - 1; i >= 0; i--)  
  51.                 {  
  52.                     buf[i] = (byte)(s & 0x000000ff);  
  53.                     s >>= 8;  
  54.                 }  
  55.             else  
  56.                 for (int i = 0; i < buf.Length; i++)  
  57.                 {  
  58.                     buf[i] = (byte)(s & 0x000000ff);  
  59.                     s >>= 8;  
  60.                 }  
  61.             return buf;  
  62.         }  
  63.   
  64.         public static byte[] getBytes(long s, bool asc)  
  65.         {  
  66.             byte[] buf = new byte[8];  
  67.             if (asc)  
  68.                 for (int i = buf.Length - 1; i >= 0; i--)  
  69.                 {  
  70.                     buf[i] = (byte)(s & 0x00000000000000ff);  
  71.                     s >>= 8;  
  72.                 }  
  73.             else  
  74.                 for (int i = 0; i < buf.Length; i++)  
  75.                 {  
  76.                     buf[i] = (byte)(s & 0x00000000000000ff);  
  77.                     s >>= 8;  
  78.                 }  
  79.             return buf;  
  80.         }  
  81.         public static short getShort(byte[] buf, bool asc)  
  82.         {  
  83.             if (buf == null)  
  84.             {  
  85.                 //throw new IllegalArgumentException("byte array is null!");   
  86.             }  
  87.             if (buf.Length > 2)  
  88.             {  
  89.                 //throw new IllegalArgumentException("byte array size > 2 !");   
  90.             }  
  91.             short r = 0;  
  92.             if (!asc)  
  93.                 for (int i = buf.Length - 1; i >= 0; i--)  
  94.                 {  
  95.                     r <<= 8;  
  96.                     r |= (short)(buf[i] & 0x00ff);  
  97.                 }  
  98.             else  
  99.                 for (int i = 0; i < buf.Length; i++)  
  100.                 {  
  101.                     r <<= 8;  
  102.                     r |= (short)(buf[i] & 0x00ff);  
  103.                 }  
  104.             return r;  
  105.         }  
  106.         public static int getInt(byte[] buf, bool asc)  
  107.         {  
  108.             if (buf == null)  
  109.             {  
  110.                 // throw new IllegalArgumentException("byte array is null!");   
  111.             }  
  112.             if (buf.Length > 4)  
  113.             {  
  114.                 //throw new IllegalArgumentException("byte array size > 4 !");   
  115.             }  
  116.             int r = 0;  
  117.             if (!asc)  
  118.                 for (int i = buf.Length - 1; i >= 0; i--)  
  119.                 {  
  120.                     r <<= 8;  
  121.                     r |= (buf[i] & 0x000000ff);  
  122.                 }  
  123.             else  
  124.                 for (int i = 0; i < buf.Length; i++)  
  125.                 {  
  126.                     r <<= 8;  
  127.                     r |= (buf[i] & 0x000000ff);  
  128.                 }  
  129.             return r;  
  130.         }  
  131.         public static long getLong(byte[] buf, bool asc)  
  132.         {  
  133.             if (buf == null)  
  134.             {  
  135.                 //throw new IllegalArgumentException("byte array is null!");   
  136.             }  
  137.             if (buf.Length > 8)  
  138.             {  
  139.                 //throw new IllegalArgumentException("byte array size > 8 !");   
  140.             }  
  141.             long r = 0;  
  142.             if (!asc)  
  143.                 for (int i = buf.Length - 1; i >= 0; i--)  
  144.                 {  
  145.                     r <<= 8;  
  146.                     r |= (buf[i] & 0x00000000000000ff);  
  147.                 }  
  148.             else  
  149.                 for (int i = 0; i < buf.Length; i++)  
  150.                 {  
  151.                     r <<= 8;  
  152.                     r |= (buf[i] & 0x00000000000000ff);  
  153.                 }  
  154.             return r;  
  155.         }  
  156.     }  
  157. }  



[csharp]  view plain copy
  1. namespace LSocket.cmd  
  2. {  
  3.     public class CommandID  
  4.     {  
  5.         /** 登陆消息命令 **/  
  6.         public static int LOGIN = 1001;  
  7.        
  8.     }  
  9. }  


服务器端代码 Java:

[java]  view plain copy
  1. package com.unity.socket;  
  2.   
  3.   
  4. import java.net.ServerSocket;  
  5. import java.net.Socket;  
  6. import java.util.HashMap;  
  7.   
  8.   
  9. public class SocketServer {  
  10.     private HashMap userMap;  
  11.   
  12.     public  SocketServer(){  
  13.          userMap=new HashMap();  
  14.     }  
  15.   
  16.     public static void main(String[] args){  
  17.         new SocketServer().startServer();  
  18.     }  
  19.   
  20.     public void startServer()  
  21.     {  
  22.         try  
  23.         {  
  24.             ServerSocket serverSocket = new ServerSocket(10000);  
  25.             System.out.println("服务器开启");  
  26.             while (true){  
  27.                 Socket socket = serverSocket.accept();  
  28.                 System.out.println("有用户登陆进来了");  
  29.                 new UserThread(socket,userMap).start();  
  30.             }  
  31.   
  32.         }catch (Exception e){  
  33.              System.out.println("服务器出现异常!" + e);  
  34.         }  
  35.     }  
  36. }  


 

[java]  view plain copy
  1. package com.unity.socket;  
  2.   
  3. import java.net.Socket;  
  4.   
  5. public class User {  
  6.     private String name;  
  7.     private Socket socket;  
  8.   
  9.   
  10.     public String getName() {  
  11.         return name;  
  12.     }  
  13.   
  14.     public void setName(String name) {  
  15.         this.name = name;  
  16.     }  
  17.   
  18.     public Socket getSocket() {  
  19.         return socket;  
  20.     }  
  21.   
  22.     public void setSocket(Socket socket) {  
  23.         this.socket = socket;  
  24.     }  
  25.   
  26. }  


[java]  view plain copy
  1. package com.unity.socket;  
  2.   
  3. import java.io.*;  
  4. import java.net.Socket;  
  5. import java.util.Iterator;  
  6.   
  7. import java.io.ByteArrayOutputStream;  
  8.   
  9. import java.io.DataOutputStream;  
  10. import java.util.HashMap;  
  11.   
  12.   
  13. public class UserThread extends Thread{  
  14.     /** 错误消息命令 **/  
  15.     public static final int             ERROR = 0;  
  16.     /** 登陆消息命令 **/  
  17.     public static final int             LOGIN = 1001;  
  18.     private Socket socket;  
  19.     private HashMap userMap;  
  20.     private User user;  
  21.     private ByteArrayOutputStream byteOutput;  
  22.     private DataOutputStream output;  
  23.     private DataInputStream input;  
  24.   
  25.     public UserThread(Socket socket,HashMap userMap){  
  26.         this.socket=socket;  
  27.         this.userMap=userMap;  
  28.     }  
  29.   
  30.     //重新初始化2个新的output   
  31.     private void initOutput()  
  32.     {  
  33.         byteOutput = new ByteArrayOutputStream();  
  34.         output = new DataOutputStream(byteOutput);  
  35.     }  
  36.   
  37.     public void sendAllUser(byte[] bytes) throws Exception  
  38.     {  
  39.         for(Iterator it = userMap.values().iterator(); it.hasNext();)  
  40.         {  
  41.             sendMessage(it.next().getSocket(),bytes);  
  42.         }  
  43.     }  
  44.   
  45.     public void sendMessage(Socket socket,byte[] bytes) throws Exception  
  46.     {  
  47.         DataOutputStream dataOutput = new DataOutputStream(socket.getOutputStream());  
  48.         dataOutput.write(bytes);  
  49.         dataOutput.flush();  
  50.     }  
  51.   
  52.     public short readShort()throws IOException{  
  53.           byte[] buf=new byte[2];  
  54.           input.read(buf);  
  55.           return ConvertType.getShort(buf,true);  
  56.     }  
  57.   
  58.     public int readInt()throws IOException{  
  59.           byte[] buf=new byte[4];  
  60.           input.read(buf);  
  61.           return ConvertType.getInt(buf, true);  
  62.     }  
  63.   
  64.     public long readLong()throws IOException{  
  65.           byte[] buf=new byte[8];  
  66.           input.read(buf);  
  67.           return ConvertType.getLong(buf, true);  
  68.     }  
  69.   
  70.    public float readFloat()throws IOException{  
  71.           byte[] buf=new byte[4];  
  72.           input.read(buf);  
  73.           return ConvertType.getFloat(buf, true);  
  74.     }  
  75.   
  76.     public String readString()throws IOException{  
  77.           int length=readInt();  
  78.           byte[] buf=new byte[length];  
  79.           input.read(buf);  
  80.           return new String(buf);  
  81.     }  
  82.   
  83.   
  84.   
  85.     public void run(){  
  86.         try{  
  87.             input = new DataInputStream(socket.getInputStream()) ;  
  88.             while (true){  
  89.                 int cmd=0;  
  90.                 cmd=readInt();  
  91.                 System.out.println("命令号:"+cmd);  
  92.                 if(cmd==ERROR){   //收空包   
  93.                     userMap.remove(user.getName());  
  94.                     Message msg=new Message();  
  95.                     msg.writeString(user.getName()+" 离开");  
  96.                     System.out.println(user.getName()+" 离开");  
  97.                     try{  
  98.                          sendAllUser(msg.getBuff().array());  
  99.                     }catch (Exception ex){  
  100.                          System.out.println("sendAllUserErr: "+ex.toString());  
  101.                      }  
  102.                     break;  
  103.                 }  
  104.                 switch (cmd){  
  105.                     case LOGIN:  
  106.                         System.out.println("读取用户名");  
  107.                         String userName = readString();  
  108.                         user = new User();  
  109.                         user.setName(userName);  
  110.                         user.setSocket(socket);  
  111.                         System.out.println(userName);  
  112.                         if(userMap.containsKey(userName)) {  
  113.                             Message msg=new Message();  
  114.                             msg.writeString("昵称重复");  
  115.                             sendMessage(socket,msg.getBuff().array());  
  116.                             msg.clear();  
  117.                             msg=null;  
  118.                         }else{  
  119.                             System.out.println("有新用户进入:" + userName);  
  120.                             userMap.put(userName, user);  
  121.                             initOutput();  
  122.                             Message msg=new Message();  
  123.                             msg.writeString("连接成功");  
  124.                             sendMessage(socket,msg.getBuff().array());  
  125.                             msg.clear();  
  126.                             msg=null;  
  127.                         }  
  128.                         break;  
  129.                 }  
  130.             }  
  131.         }catch (Exception e){  
  132.              e.printStackTrace();  
  133.              userMap.remove(user.getName());  
  134.              Message msg=new Message();  
  135.              msg.writeString(user.getName()+" 离开");  
  136.             System.out.println(user.getName()+" 离开");  
  137.             try{  
  138.                 sendAllUser(msg.getBuff().array());  
  139.             }catch (Exception ex){  
  140.                 System.out.println("sendAllUserErr: "+ex.toString());  
  141.             }  
  142.   
  143.         }  
  144.     }  
  145. }  
[java]  view plain copy
  1. package com.unity.socket;  
  2.   
  3. import java.nio.ByteBuffer;  
  4.   
  5. import com.unity.socket.ConvertType;  
  6.   
  7. public class Message {  
  8.     private ByteBuffer buf;  
  9.     public Message(){  
  10.         buf=ByteBuffer.allocate(0);  
  11.     }  
  12.   
  13.     public ByteBuffer getBuff(){  
  14.         return  buf;  
  15.     }  
  16.   
  17.     public void clear(){  
  18.         buf.clear();  
  19.     }  
  20.   
  21.     public void addSize(int len){  
  22.         ByteBuffer tmpbuf=ByteBuffer.allocate(buf.capacity()+len);  
  23.         buf=null;  
  24.         buf=tmpbuf;  
  25.     }  
  26.   
  27.     public void writeByte(byte b){  
  28.        addSize(1);  
  29.        buf.put(b);  
  30.     }  
  31.   
  32.     public void write(byte[] b){  
  33.         addSize(b.length);  
  34.         buf.put(b);  
  35.     }  
  36.   
  37.      public void writeShort(short b){  
  38.         addSize(2);  
  39.         buf.put(ConvertType.getBytes(b,true));  
  40.     }  
  41.   
  42.     public void writeInt(int b){  
  43.         addSize(4);  
  44.         buf.put(ConvertType.getBytes(b,true));  
  45.     }  
  46.   
  47.      public void writeLong(long b){  
  48.         addSize(8);  
  49.         buf.put(ConvertType.getBytes(b,true));  
  50.     }  
  51.   
  52.     public void writeFloat(float b){  
  53.         addSize(4);  
  54.         buf.put(ConvertType.getBytes(b,true)) ;  
  55.     }  
  56.   
  57.     public void writeString(String s){  
  58.         byte[] b= new byte[200];  
  59.         b=s.getBytes();  
  60.         addSize(4+b.length);  
  61.         buf.put(ConvertType.getBytes(b.length,true));  
  62.         buf.put(s.getBytes());  
  63.     }  
  64. }  


[java]  view plain copy
  1. package com.unity.socket;  
  2.   
  3. public class ConvertType   
  4. {  
  5.     public ConvertType()  
  6.     {  
  7.           
  8.     }  
  9.   
  10.     public final static byte[] getBytes(float s,boolean asc){  
  11.         int buf=(int)(s*100);  
  12.         return getBytes(buf,asc);  
  13.     }  
  14.   
  15.      public final static float getFloat(byte[] buf,boolean asc){  
  16.         int i=getInt(buf,asc);  
  17.         float s=(float)i;  
  18.         return s/100;  
  19.     }  
  20.   
  21.     public final static byte[] getBytes(short s, boolean asc)  
  22.     {  
  23.         byte[] buf = new byte[2];  
  24.         if (asc)   
  25.         {  
  26.             for (int i = buf.length - 1; i >= 0; i--)   
  27.             {          
  28.                 buf[i] = (byte) (s & 0x00ff);  
  29.                 s >>= 8;  
  30.              }  
  31.         }  
  32.         else  
  33.         {    
  34.             for (int i = 0; i < buf.length; i++)   
  35.             {  
  36.          
  37.                 buf[i] = (byte) (s & 0x00ff);  
  38.                 s >>= 8;  
  39.             }  
  40.         }  
  41.         return buf;  
  42.       }  
  43.       public final static byte[] getBytes(int s, boolean asc) {  
  44.         byte[] buf = new byte[4];  
  45.         if (asc)  
  46.           for (int i = buf.length - 1; i >= 0; i--) {  
  47.             buf[i] = (byte) (s & 0x000000ff);  
  48.             s >>= 8;  
  49.           }  
  50.         else  
  51.           for (int i = 0; i < buf.length; i++) {  
  52.             buf[i] = (byte) (s & 0x000000ff);  
  53.             s >>= 8;  
  54.           }  
  55.         return buf;  
  56.       }  
  57.       public final static byte[] getBytes(long s, boolean asc) {  
  58.         byte[] buf = new byte[8];  
  59.         if (asc)  
  60.           for (int i = buf.length - 1; i >= 0; i--) {  
  61.             buf[i] = (byte) (s & 0x00000000000000ff);  
  62.             s >>= 8;  
  63.           }  
  64.         else  
  65.           for (int i = 0; i < buf.length; i++) {  
  66.             buf[i] = (byte) (s & 0x00000000000000ff);  
  67.             s >>= 8;  
  68.           }  
  69.         return buf;  
  70.       }  
  71.       public final static short getShort(byte[] buf, boolean asc)   
  72.       {  
  73.             if (buf == null)   
  74.             {  
  75.               throw new IllegalArgumentException("byte array is null!");  
  76.             }  
  77.             if (buf.length > 2)   
  78.             {  
  79.               throw new IllegalArgumentException("byte array size > 2 !");  
  80.             }  
  81.             short r = 0;  
  82.             if (!asc)  
  83.               for (int i = buf.length - 1; i >= 0; i--) {  
  84.                 r <<= 8;  
  85.                 r |= (buf[i] & 0x00ff);  
  86.               }  
  87.             else  
  88.               for (int i = 0; i < buf.length; i++) {  
  89.                 r <<= 8;  
  90.                 r |= (buf[i] & 0x00ff);  
  91.               }  
  92.             return r;  
  93.       }  
  94.       public final static int getInt(byte[] buf, boolean asc) {  
  95.         if (buf == null) {  
  96.           throw new IllegalArgumentException("byte array is null!");  
  97.         }  
  98.         if (buf.length > 4) {  
  99.           throw new IllegalArgumentException("byte array size > 4 !");  
  100.         }  
  101.         int r = 0;  
  102.         if (!asc)  
  103.           for (int i = buf.length - 1; i >= 0; i--) {  
  104.             r <<= 8;  
  105.             r |= (buf[i] & 0x000000ff);  
  106.           }  
  107.         else  
  108.           for (int i = 0; i < buf.length; i++) {  
  109.             r <<= 8;  
  110.             r |= (buf[i] & 0x000000ff);  
  111.           }  
  112.         return r;  
  113.       }  
  114.       public final static long getLong(byte[] buf, boolean asc) {  
  115.         if (buf == null) {  
  116.           throw new IllegalArgumentException("byte array is null!");  
  117.         }  
  118.         if (buf.length > 8) {  
  119.           throw new IllegalArgumentException("byte array size > 8 !");  
  120.         }  
  121.         long r = 0;  
  122.         if (!asc)  
  123.           for (int i = buf.length - 1; i >= 0; i--) {  
  124.             r <<= 8;  
  125.             r |= (buf[i] & 0x00000000000000ff);  
  126.           }  
  127.         else  
  128.           for (int i = 0; i < buf.length; i++) {  
  129.             r <<= 8;  
  130.             r |= (buf[i] & 0x00000000000000ff);  
  131.           }  
  132.         return r;  
  133.       }  
  134.       
  135. }  

 


 

很简单的demo,有一定的可扩展性,需要工程的可以下载来看,下载链接

http://download.csdn.net/detail/genius840215/4187126


你可能感兴趣的:(Unity3d)