unity3d socket编程案例

Unity3D网络编程之Socket通信实战演示 在现代游戏开发中,网络功能已成为不可或缺的核心模块之一。Unity3D作为全球主流的游戏引擎,凭借其强大的跨平台能力与灵活的C#脚本系统,成为实现多人在线游戏与实时交互应用的理想选择。本章将从整体架构角度出发,剖析Unity3D在网络通信中的角色定位,探讨其基于Socket的底层通信机制,并与传统同步通信模型进行对比。Unity采用C#语言作为核心开发语言,其网络编程模型支持同步与异步两种方式,开发者可根据项目需求灵活选择。 阅读详情

转自:http://blog.youkuaiyun.com/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<String,User> userMap;  
  11.   
  12.     public  SocketServer(){  
  13.          userMap=new HashMap<String, User>();  
  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<String,User> userMap;  
  20.     private User user;  
  21.     private ByteArrayOutputStream byteOutput;  
  22.     private DataOutputStream output;  
  23.     private DataInputStream input;  
  24.   
  25.     public UserThread(Socket socket,HashMap<String,User> 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<User> 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.youkuaiyun.com/detail/genius840215/4187126


unity socket应用实例 unity socket应用实例,经典应用套接字做网络游戏开发 立即下载

相关推荐

Blender点云渲染实战:用Geometry Nodes快速搞定论文配图(附Cycles渲染技巧)

本文详细介绍了如何利用Blender的Geometry Nodes系统,高效地将三维点云数据转化为高质量的科研论文配图。通过实战步骤,从数据导入、节点化几何处理、材质赋予到Cycles渲染引擎的优化设置,手把手教你制作出专业、美观的可视化图像,助力科研成果展示。

hp777的博客 265

byte[] int[] short[] 转换

import java.nio.ByteOrder; public class BytesTransUtils { private String TAG = "BytesTransUtils"; private static BytesTransUtils instance = null; private BytesTransUtils() {

jjdujiang的专栏 475

FPGA以太网接口设计避坑指南:GMII与RGMII时序转换的三种实现方案对比

本文深入解析FPGA以太网接口设计中GMII与RGMII时序转换的三种实现方案,包括Xilinx官方IP核、手工原语逻辑和开源方案gmii_to_rgmii。通过对比分析各方案的优缺点和适用场景,为工程师提供技术选型指南,帮助避免常见设计陷阱,提升高速网络设备开发的效率和可靠性。

weixin_42570484的博客 381

【Unity3D】异步Socket通讯

同步 Socket 通讯中的 Accept、Connect、Receive 等方法会阻塞当前线程,当前线程必须等待这些方法执行完,才会继续往下执行,用户需要另开线程执行这些耗时方法,否则会阻塞主线程,导致 UI 卡顿。异步 Socket 通讯中,通过 BeginAccept、EndAccept、BeginConnect、EndConnect、BeginReceive、EndReceive 等方法实现请求、连接、收消息等效果,这些方法通过回调(Callback)的方式实现异步通讯,并且不会阻塞主线程。

little_fat_sheep 5079

【实验】Linux下完全卸载oracle单实例(亲身体验完整版)

停止oracle数据库服务 停止监听 卸载数据库实例 因为自己懒得再弄dbca图形化界面啥的,直接采用dbca静默删除数据库实例,命令如下 dbca -silent -deleteDatabase -sourcedb orclhq -sid orcl -sysDBAUserName orcl -sysDBAPassword zte [oracle@slave ~]$ dbca -silent ...

萝卜吃鱼914的博客 1945

智能工厂评估模型研究

摘要:通过对国内外现有智能制造评估模型的研究,结合重庆制造业行业领跑者与落后者之间差距大的现状,以实现全要素全连接的数字化工厂为出发点,融合工业互联网标识,构建实践可行的智能工厂评估模型推动中小型企业参与智能制造转型,缓和两极分化问题。本评估模型包含工厂体系架构的3个层级,提供用于推动智能制造转型的参考,包括设计、生产、管理的全过程评估。关键词:智能制造评估模型;智能制造转型;全连接工厂;工业互联网标识0 引言受行业需求与技术创新的影响,全球制造业在历经了工业1.0机械化、工业2.0电气化和工业3.0自动

罗伯特技术屋 677

Unity Sockt 简单例子

using UnityEngine; public class SocketManager { #region 单例类 private static SocketManager instance; private SocketManager() { } public static SocketManager Instance { ...

llllaeeee的专栏 220

【AI大模型应用开发实战】大型语言模型评估指南白皮书(LLM Eval)

近年来,大型语言模型(LLM)在自然语言处理领域取得了重大进展,例如 GPT-3 和 Chat-GPT。这些模型经过大型数据集的训练,在文本相关任务中表现出卓越的能力,甚至超越了人类。本文将简要介绍如何验证 LLMs 性能的评估指标。自然语言处理(NLP)是人工智能的一个领域,涉及计算机和人类语言之间的交互。NLP 的基本任务之一是语言建模 (LM),它涉及构建统计模型来分析和生成自然语言。LM 已成为推进机器语言智能的关键方法,使机器能够执行机器翻译、情感分析和对话系统等任务。

AI天才研究院 1013

Unity Socket 初级入门

在unity运行socket类收发消息的踩雷

qq_43016637的博客 978

QGis二次开发 —— 1.1、ubuntu24.04下搭建QGis3.40.12二次开发环境(附:全部问题解决方法)

QGis二次开发 —— 1.1、ubuntu24.02下搭建QGis3.40.12二次开发环境(附:全部问题解决方法)

250

恶劣天气下的分割鲁棒性:雨雪雾干扰消除

恶劣天气下的分割鲁棒性:雨雪雾干扰消除​ ,人工智能,计算机视觉,大模型,AI,本文围绕恶劣天气下语义分割鲁棒性及雨雪雾干扰消除展开,分析了雨雪雾对图像和分割任务的影响,介绍了基于图像增强、深度学习等现有解决方法,以及针对不同干扰的具体方案,还探讨了提高分割鲁棒性的策略、实验评估情况,指出当前面临复杂天气、数据缺乏、实时性等挑战,并展望了端到端模型、无监督学习等未来发展趋势,为该领域研究提供了全面参考。

不踩坑,不知道坑有多深;不总结,踩过的坑白踩。 17万+

unity3d Socket异步连接(附带一个案例)

socket同步 同步就是有阻塞,比如接收数据时如果没有数据就等待,等到有数据了再执行下一步代码。 socket异步 异步就不用等待,比如指定接收数据后就会继续执行一下步代码,等到有数据了再跳出当前执行的代码转去执行异步调用。 同步的话通常要配合多线程(否则在阻塞的时候当前线程会停止,如果当前线程是UI线程就表现出好像界面停止的样子)。 左边是客户端右边是服务器 服务器储存客户集合客户类(服务器的) using System; using System.Collections....

qq_57896821的博客 2642

矩阵理论与应用:数理经济学中的投入产出模型分析

1. 背景介绍 矩阵理论是现代数学中的一个重要分支,它在各个领域都有广泛的应用。其中,投入-产出模型是矩阵理论在经济学中的一种应用,它可以用来分析一个国家或地区的经济结构和发展趋势。本文将介绍投入-产出模型的基本概念和原理,并通过实例来说明其应用。 2. 核心概念与联系 投入-产出模型是一

AI天才研究院 1486

Unity3D 异步Socket 网络编程

简单的异步socket示例 简单过一下主要使用到的相关API: public class Socket : IDisposable { public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType); // 连接指定地址&amp;端口 public void Connect(EndPoint remoteEP); // 异步接收, 指定callback函数处理到来的函数(自动创建线

whibalck的博客 2322

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

C#中Socket通信编程的同步实现

 目录(?)[+] Socket编程基础什么是Socket编程的同步实现如何实现Socket同步通信 服务端 基本流程 客户端 基本流程代码示例同样地我们现在来运行客户端程序这样客户端就可以和服务端进行通信了 总结 本文通过分析和总结C#中Socket通信编程的关键技术,按照同步实现的方式实现了一个简单的Socket聊天程序,目的是通

潘晓宇(panxiaoyu)的专栏 1060

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

梦想成真---Socket技术详解

梦想成真—Socket技术详解 1.序 1.1计算机网络 计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。 计算机网络的分类与一般的事物分类方法一样,可以按事物所具有的不同性质特点分类。计算机网络通俗地讲就是由多台计算机通过传输介质和软件物理连接在一起组成的。总的来说计算机网络的组成基本上包括:计算机、网络操作系统、传输介质以及相应的应用软件四部分。 1.2 网络编程 网络

weixin_41563161的博客 857

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Socket编程之TcpClient、TcpListener在Unity3D中的应用

经过一段时间的学习,对于TCP/IP协议有了一定的认识,大概知道了TCP协议通信的原理,接下来主要实现用TcpClient、TcpListener两个封装类和stream来实现一个小的demo:用vs建一个工程作为服务器,然后用Unity引擎作为客户端,实现客户端和服务器,客户端和客户端之间的通信。 由于入坑试验多次,这里强调一下通信时候的数据转换,当在客户端发送信息的时候,会将用户输入的字符串...

Mickey丶笑风沙 3871

《Unity3D网络游戏实战》学习与实践

实现了一个简单的聊天室

zaizai1007的博客 1418

[Unity3D ARPG网络游戏编程实践] 网络连接 :unity NetWork与socket的对比(一)

unity3d ARPG网络游戏编程实践 作者:A神 目录 1 网络连接 (unity NetWork与socket的对比) 2 登录界面 (登录协议与模型定制 及流程开发) 3 角色选择 (进入游戏后的角色选择界面及通信流程) 4 角色创建 (角色创建的界面与流程) 5 进入场景 (选择角色后 进入场景实例化自身及场景信息流程) 6 游戏UI    (进入游戏后的UI界面 更新 及

青峰专栏 7807

Warensoft Unity3D 通信库项目简介

Warensoft Unity3D 通信库项目简介 项目下载地址:http://wucl.codeplex.com 该类库是专门为Unity3D编写的一个高性能通信库,其中包括了若干十分易于使用的Http通信类以及Socket通信类.另外最特别之处在于,它引入了一个全新的,基于Http协议的数据库访问组件,可以轻松访问MS SQL SERVER2005+. Warensoft Unit...

weixin_30376509的博客 214

[Unity3D ARPG网络游戏编程实践]1——初识unity网络编程

[Unity3D ARPG网络游戏编程实践] 想杀人了,百度了半天也不知道本地服务怎么写,结果资源里的服务器竟然可以用了~~~~(&gt;_&lt;)~~~~ 使用了两种方法1 这个方法特别郁闷,自己写服务器,自己写客户端可以通讯。可是这个服务器用在 [Unity3D ARPG网络游戏编程实践] 中就不能链接成功,还好资源里带有启动本地服务的程序,不会原因,不懂服务器链接的原理宣雨...

dichuzhi7828的博客 275

Unity3D研究院之C#使用Socket与HTTP连接服务器传输数据包(四十三)

http://www.xuanyusong.com/archives/1948

chenluwolf的专栏 1855

unity3D中使用Socket进行数据通信(一)

公司今年3D产品的工作中心主要集中在提高产品深度上,通过对竞争产品的分析,发现我们的缺陷在于多人在线与后台管理部分,多人在线使用unity自带的Network能够搞定,后台部分前段时间主要研究了下Sqlite。因为sqlite本身不带server,作为数据库仅仅是一个文件,sqlite放在server上与client通信的需求事实上就是多个client訪问同一个文件了。查了一些资料,有非常...

weixin_34202952的博客 316

Unity3D TCP聊天应用开发:从Socket通信到C/S架构实战

网络通信是实时交互应用的核心骨架,其基础在于理解客户端-服务器(C/S)模型与Socket编程原理。TCP协议通过三次握手建立可靠连接,确保数据有序、完整传输,为聊天、指令同步等场景提供稳定保障。在Unity3D中实现网络功能,需掌握多线程或异步编程,以处理网络IO操作,避免阻塞主线程。通过设计应用层消息协议(如长度+内容的格式)解决TCP粘包问题,并利用心跳机制维护连接活性。本文以构建一个完整的TCP聊天室为例,详解服务器端监听、连接管理、消息广播,以及Unity客户端的连接、数据收发与UI交互,涵盖**

weixin_30905981的博客 284
上一篇: U3d架构系列之-FSM有限状态机设计
下一篇: Unity中的网络编程
我是一纸巾
博客等级 码龄12年 14粉丝 37原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值