unity3D Net

原文地址:http://www.unitymanual.com/forum.php?mod=viewthread&tid=21419&highlight=Http


最近比较忙,有段时间没写博客拉。最近项目中需要使用HTTP与Socket,雨松MOMO把自己这段时间学习的资料整理一下。有关Socket与HTTP的基础知识MOMO就不赘述拉,不懂得朋友自己谷歌吧。我们项目的需求是在登录的时候使用HTTP请求,游戏中其它的请求都用Socket请求,比如人物移动同步坐标,同步关卡等等。

1.Socket

         Socket不要写在脚本上,如果写在脚本上游戏场景一旦切换,那么这条脚本会被释放掉,Socket会断开连接。场景切换完毕后需要重新在与服务器建立Socket连接,这样会很麻烦。所以我们需要把Socket写在一个单例的类中,不用继承MonoBehaviour。这个例子我模拟一下,主角在游戏中移动,时时向服务端发送当前坐标,当服务器返回同步坐标时角色开始同步服务端新角色坐标。

Socket在发送消息的时候采用的是字节数组,也就是说无论你的数据是 int float short object 都会将这些数据类型先转换成byte[] , 目前在处理发送的地方我使用的是数据包,也就是把(角色坐标)结构体object转换成byte[]发送, 这就牵扯一个问题, 如何把结构体转成字节数组, 如何把字节数组回转成结构体。请大家接续阅读,答案就在后面,哇咔咔。

直接上代码

JFSocket.cs 该单例类不要绑定在任何对象上

[AppleScript] 纯文本查看 复制代码
?
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
< font face = "Verdana," > using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
  
public class JFSocket
{
  
     / / Socket客户端对象
     private Socket clientSocket;
     / / JFPackage.WorldPackage是我封装的结构体,
     / / 在与服务器交互的时候会传递这个结构体
     / / 当客户端接到到服务器返回的数据包时,我把结构体 add 存在链表中。
     public List worldpackage;
     / / 单例模式
     private static JFSocket instance;
     public static JFSocket GetInstance ( )
     {
         if ( instance = = null )
         {
             instance = new JFSocket ( ) ;
         }
         return instance;
      }     
  
     / / 单例的构造函数
     JFSocket ( )
     {
         / / 创建Socket对象, 这里我的连接类型是TCP
         clientSocket = new Socket ( AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp ) ;
         / / 服务器IP地址
         IPAddress ipAddress = IPAddress.Parse ( "192.168.1.100" ) ;
         / / 服务器端口
         IPEndPoint ipEndpoint = new IPEndPoint ( ipAddress , 10060 ) ;
         / / 这是一个异步的建立连接,当连接建立成功时调用connectCallback方法
         IAsyncResult result = clientSocket.BeginConnect ( ipEndpoint , new AsyncCallback ( connectCallback ) , clientSocket ) ;
         / / 这里做一个超时的监测,当连接超过 5 秒还没成功表示超时
         bool success = result .AsyncWaitHandle.WaitOne ( 5000 , true ) ;
         if ( !success )
            {
                / / 超时
               Closed ( ) ;
             Debug.Log ( "connect Time Out" ) ;
         } else
         {
             / / 与socket建立连接成功,开启线程接受服务端数据。
             worldpackage = new List ( ) ;
             Thread thread = new Thread ( new ThreadStart ( ReceiveSorket ) ) ;
                 thread.IsBackground = true ;
             thread.Start ( ) ;
         }
     }
  
     private void connectCallback ( IAsyncResult asyncConnect )
     {
         Debug.Log ( "connectSuccess" ) ;
     }
  
     private void ReceiveSorket ( )
     {
         / / 在这个线程中接受服务器返回的数据
         while ( true )
         {
  
             if ( !clientSocket.Connected )
             {
                 / / 与服务器断开连接跳出循环
                 Debug.Log ( "Failed to clientSocket server." ) ;
                 clientSocket.Close ( ) ;
                 break;
             }
             try
             {
                 / / 接受数据保存至bytes当中
                 byte[] bytes = new byte[ 4096 ];
                 / / Receive方法中会一直等待服务端回发消息
                 / / 如果没有回发会一直在这里等着。
                 int i = clientSocket.Receive ( bytes ) ;
                 if ( i < = 0 )
                 {
                     clientSocket.Close ( ) ;
                     break;
                 }   
  
                 / / 这里条件可根据你的情况来判断。
                 / / 因为我目前的项目先要监测包头长度,
                 / / 我的包头长度是 2 ,所以我这里有一个判断
                 if ( bytes.Length > 2 )
                 {
                     SplitPackage ( bytes , 0 ) ;
                 } else
                 {
                     Debug.Log ( "length is not  >  2" ) ;
                 }
  
              }
              catch ( Exception e )
              {
                 Debug.Log ( "Failed to clientSocket error." + e ) ;
                 clientSocket.Close ( ) ;
                 break;
              }
         }
     }   
  
     private void SplitPackage ( byte[] bytes , int index )
     {
         / / 在这里进行拆包,因为一次返回的数据包的数量是不定的
         / / 所以需要给数据包进行查分。
         while ( true )
         {
             / / 包头是 2 个字节
             byte[] head = new byte[ 2 ];
             int headLengthIndex = index + 2 ;
             / / 把数据包的前两个字节拷贝出来
             Array.Copy ( bytes , index , head , 0 , 2 ) ;
             / / 计算包头的长度
             short length = BitConverter.ToInt 16 ( head , 0 ) ;
             / / 当包头的长度大于 0 那么需要依次把相同长度的byte数组拷贝出来
             if ( length > 0 )
             {
                 byte[] data = new byte[length];
                 / / 拷贝出这个包的全部字节数
                 Array.Copy ( bytes , headLengthIndex , data , 0 , length ) ;
                 / / 把数据包中的字节数组强制转换成数据包的结构体
                 / / BytesToStruct ( ) 方法就是用来转换的
                 / / 这里需要和你们的服务端程序商量,
                 JFPackage.WorldPackage wp = new JFPackage.WorldPackage ( ) ;
                 wp = ( JFPackage.WorldPackage ) BytesToStruct ( data , wp.GetType ( ) ) ;
                 / / 把每个包的结构体对象添加至链表中。
                 worldpackage.Add ( wp ) ;
                 / / 将索引指向下一个包的包头
                 index  =  headLengthIndex + length;
  
             } else
             {
                 / / 如果包头为 0 表示没有包了,那么跳出循环
                 break;
             }
         }
     }   
  
     / / 向服务端发送一条字符串
     / / 一般不会发送字符串 应该是发送数据包
     public void SendMessage ( string str )
     {
          byte[] msg = Encoding.UTF 8. GetBytes ( str ) ;
  
         if ( !clientSocket.Connected )
         {
             clientSocket.Close ( ) ;
             return ;
         }
         try
         {
             / / int i = clientSocket.Send ( msg ) ;
             IAsyncResult asyncSend = clientSocket.BeginSend ( msg , 0 , msg.Length , SocketFlags.None , new AsyncCallback ( sendCallback ) , clientSocket ) ;
             bool success = asyncSend.AsyncWaitHandle.WaitOne ( 5000 , true ) ;
             if ( !success )
                {
                   clientSocket.Close ( ) ;
                 Debug.Log ( "Failed to SendMessage server." ) ;
             }
         }
         catch
         {
              Debug.Log ( "send message error" ) ;
         }
     }
  
     / / 向服务端发送数据包,也就是一个结构体对象
     public void SendMessage ( object obj )
     {
  
         if ( !clientSocket.Connected )
         {
             clientSocket.Close ( ) ;
             return ;
         }
         try
         {
             / / 先得到数据包的长度
             short size = ( short ) Marshal.SizeOf ( obj ) ;
             / / 把数据包的长度写入byte数组中
             byte [] head = BitConverter.GetBytes ( size ) ;
             / / 把结构体对象转换成数据包,也就是字节数组
             byte[] data = StructToBytes ( obj ) ;
  
             / / 此时就有了两个字节数组,一个是标记数据包的长度字节数组, 一个是数据包字节数组,
             / / 同时把这两个字节数组合并成一个字节数组
  
             byte[] newByte = new byte[head.Length + data .Length];
             Array.Copy ( head , 0 , newByte , 0 , head.Length ) ;
             Array.Copy ( data , 0 , newByte , head.Length , data .Length ) ;
  
             / / 计算出新的字节数组的长度
             int length = Marshal.SizeOf ( size ) + Marshal.SizeOf ( obj ) ;
  
             / / 向服务端异步发送这个字节数组
             IAsyncResult asyncSend = clientSocket.BeginSend ( newByte , 0 , length , SocketFlags.None , new AsyncCallback ( sendCallback ) , clientSocket ) ;
             / / 监测超时
             bool success = asyncSend.AsyncWaitHandle.WaitOne ( 5000 , true ) ;
             if ( !success )
                {
                   clientSocket.Close ( ) ;
                 Debug.Log ( "Time Out !" ) ;
             }
  
         }
         catch ( Exception e )
         {
              Debug.Log ( "send message error: " + e ) ;
         }
     }
  
     / / 结构体转字节数组
     public byte[] StructToBytes ( object structObj )
     {
  
         int size = Marshal.SizeOf ( structObj ) ;
         IntPtr buffer =  Marshal.AllocHGlobal ( size ) ;
         try
           {
               Marshal.StructureToPtr ( structObj , buffer , false ) ;
             byte[]  bytes  =   new byte[size];
             Marshal.Copy ( buffer , bytes , 0 , size ) ;
             return   bytes;
           }
           finally
           {
               Marshal.FreeHGlobal ( buffer ) ;
           }
     }
     / / 字节数组转结构体
     public object BytesToStruct ( byte[] bytes ,   Type   strcutType )
     {
         int size = Marshal.SizeOf ( strcutType ) ;
         IntPtr buffer = Marshal.AllocHGlobal ( size ) ;
           try
          {
                 Marshal.Copy ( bytes , 0 , buffer , size ) ;
                return  Marshal.PtrToStructure ( buffer ,   strcutType ) ;
           }
         finally
           {
               Marshal.FreeHGlobal ( buffer ) ;
           }  
  
     }
  
     private void sendCallback ( IAsyncResult asyncSend )
     {
  
     }
  
     / / 关闭Socket
     public void Closed ( )
     {
  
         if ( clientSocket ! = null & & clientSocket.Connected )
         {
             clientSocket.Shutdown ( SocketShutdown.Both ) ;
             clientSocket.Close ( ) ;
         }
         clientSocket = null;
     }
  
} < / font >

为了与服务端达成默契,判断数据包是否完成。我们需要在数据包中定义包头 ,包头一般是这个数据包的长度,也就是结构体对象的长度。正如代码中我们把两个数据类型 short 和 object 合并成一个新的字节数组。然后是数据包结构体的定义,需要注意如果你在做IOS和 android的话数据包中不要包含数组,不然在结构体转换byte数组的时候会出错。Marshal.StructureToPtr () error : Attempting to JIT compile methodJFPackage.cs
[AppleScript]  纯文本查看  复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
  
public class JFPackage
{
     / / 结构体序列化
     [System.Serializable]
     / / 4 字节对齐 iphone 和 android上可以 1 字节对齐
     [StructLayout ( LayoutKind.Sequential , Pack = 4 ) ]
     public struct WorldPackage
     {
          public byte mEquipID;
          public byte mAnimationID;
          public byte mHP;
           public short mPosx;
           public short mPosy;
           public short mPosz;
           public short mRosx;
           public short mRosy;
           public short mRosz;
  
          public WorldPackage ( short posx , short posy , short posz , short rosx , short rosy , short rosz , byte equipID , byte animationID , byte hp )
          {
             mPosx = posx;
             mPosy = posy;
             mPosz = posz;
             mRosx = rosx;
             mRosy = rosy;
             mRosz = rosz;
             mEquipID = equipID;
             mAnimationID = animationID;
             mHP = hp;
          }
  
     }
  
}

在脚本中执行发送数据包的动作,在Start方法中得到Socket对象。
[AppleScript]  纯文本查看  复制代码
?
01
02
03
04
05
06
07
08
09
10
11
public JFSocket mJFsorket;
 
 
 
void Start ( )
 
{
 
     mJFsorket = JFSocket.GetInstance ( ) ;
 
}

让角色发生移动的时候,调用该方法向服务端发送数据。
[AppleScript]  纯文本查看  复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
void SendPlayerWorldMessage ( )
{
              / / 组成新的结构体对象,包括主角坐标旋转等。
      Vector 3 PlayerTransform = transform.localPosition;
      Vector 3 PlayerRotation = transform.localRotation.eulerAngles;
              / / 用short的话是 2 字节,为了节省包的长度。这里乘以 100 避免使用float 4 字节。当服务器接受到的时候小数点向前移动两位就是真实的float数据
      short px =  ( short ) ( PlayerTransform.x * 100 ) ;
      short py =  ( short ) ( PlayerTransform.y * 100 ) ;
      short pz =  ( short ) ( PlayerTransform.z * 100 ) ;
      short rx =  ( short ) ( PlayerRotation.x * 100 ) ;
      short ry =  ( short ) ( PlayerRotation.y * 100 ) ;
      short rz =  ( short ) ( PlayerRotation.z * 100 ) ;
      byte equipID = 1 ;
      byte animationID = 9 ;
      byte hp = 2 ;
      JFPackage.WorldPackage wordPackage = new JFPackage.WorldPackage ( px , py , pz , rx , ry , rz , equipID , animationID , hp ) ;
              / / 通过Socket发送结构体对象
      mJFsorket.SendMessage ( wordPackage ) ;
}

接着就是客户端同步服务器的数据,目前是测试阶段所以写的比较简陋,不过原理都是一样的。哇咔咔!!
[AppleScript]  纯文本查看  复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/ / 上次同步时间
    private float mSynchronous;
 
void Update ( )
{
 
     mSynchronous + = Time.deltaTime;
     / / 在Update中每 0.5 s的时候同步一次
     if ( mSynchronous > 0.5 f )
     {
         int count = mJFsorket.worldpackage.Count;
         / / 当接受到的数据包长度大于 0 开始同步
         if ( count > 0 )
         {
                             / / 遍历数据包中 每个点的坐标
             foreach ( JFPackage.WorldPackage wp in mJFsorket.worldpackage )
             {
                 float x = ( float ) ( wp.mPosx / 100.0 f ) ;
                 float y = ( float ) ( wp.mPosy / 100.0 f ) ;
                 float z = ( float ) ( wp.mPosz / 100.0 f ) ;
 
                 Debug.Log ( "x = " + x + " y = " + y + " z = " + z ) ;
                   / / 同步主角的新坐标
                 mPlayer.transform. position = new Vector 3 ( x , y , z ) ;
             }
                             / / 清空数据包链表
             mJFsorket.worldpackage.Clear ( ) ;
         }
         mSynchronous = 0 ;
     }
}

主角移动的同时,通过Socket时时同步坐标喔。。有没有感觉这个牛头人非常帅气 哈哈哈。
对于Socket的使用,我相信没有比MSDN更加详细的了。 有关Socket 同步请求异步请求的地方可以参照MSDN  链接地址给出来了,好好学习吧,嘿嘿。 http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.aspx上述代码中我使用的是Thread() 没有使用协同任务StartCoroutine() ,原因是协同任务必需要继承MonoBehaviour,并且该脚本要绑定在游戏对象身上。问题绑定在游戏对象身上切换场景的时候这个脚本必然会释放,那么Socket肯定会断开连接,所以我需要用Thread,并且协同任务它并不是严格意义上的多线程。 2.HTTP HTTP请求在Unity我相信用的会更少一些,因为HTTP会比SOCKET慢很多,因为它每次请求完都会断开。废话不说了, 我用HTTP请求制作用户的登录。用HTTP请求直接使用Unity自带的www类就可以,因为HTTP请求只有登录才会有, 所以我就在脚本中来完成, 使用 www 类 和 协同任务StartCoroutine()。
[AppleScript]  纯文本查看  复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LoginGlobe : MonoBehaviour {
  
     void Start ( )
     {
         / / GET请求
         StartCoroutine ( GET ( "http://xuanyusong.com/" ) ) ;
  
     }
  
     void Update ( )
     {
  
     }
  
     void OnGUI ( )
     {
  
     }
  
     / / 登录
     public void LoginPressed ( )
     {
         / / 登录请求 POST 把参数写在字典用 通过www类来请求
         Dictionary < string , string > dic = new Dictionary < string , string > ( ) ;
         / / 参数
         dic.Add ( "action" , "0" ) ;
         dic.Add ( "usrname" , "xys" ) ;
         dic.Add ( "psw" , "123456" ) ;
  
         StartCoroutine ( POST ( "http://192.168.1.12/login.php" , dic ) ) ;
  
     }
     / / 注册
     public void SingInPressed ( )
     {
         / / 注册请求 POST
         Dictionary < string , string > dic = new Dictionary < string , string > ( ) ;
         dic.Add ( "action" , "1" ) ;
         dic.Add ( "usrname" , "xys" ) ;
         dic.Add ( "psw" , "123456" ) ;
  
         StartCoroutine ( POST ( "http://192.168.1.12/login.php" , dic ) ) ;
     }
  
     / / POST请求
      IEnumerator POST ( string url , Dictionary < string , string > post )
     {
         WWWForm form = new WWWForm ( ) ;
         foreach ( KeyValuePair < string , string > post_arg in post )
         {
                form.AddField ( post_arg.Key , post_arg.Value ) ;
         }
  
         WWW www = new WWW ( url , form ) ;
         yield return www;
  
         if ( www. error ! = null )
         {
             / / POST请求失败
             Debug.Log ( "error is :" + www. error ) ;
  
         } else
         {
             / / POST请求成功
              Debug.Log ( "request ok : " + www. text ) ;
         }
     }
  
     / / GET请求
     IEnumerator GET ( string url )
     {
  
         WWW www = new WWW ( url ) ;
         yield return www;
  
         if ( www. error ! = null )
         {
             / / GET请求失败
             Debug.Log ( "error is :" + www. error ) ;
  
         } else
         {
             / / GET请求成功
              Debug.Log ( "request ok : " + www. text ) ;
         }
     }
  
}

如果想通过HTTP传递二进制流的话 可以使用 下面的方法。
[AppleScript]  纯文本查看  复制代码
?
1
2
3
4
5
6
7
WWWForm wwwForm = new WWWForm ( ) ;
 
      byte[] byteStream = System.Text.Encoding.Default.GetBytes ( stream ) ;
 
      wwwForm.AddBinaryData ( "post" , byteStream ) ;
 
      www = new WWW ( Address , wwwForm ) ;

目前Socket数据包还是没有进行加密算法,后期我会补上。欢迎讨论,互相学习互相进度 加油,蛤蛤。

下载地址我不贴了,因为没有服务端的东西 运行也看不到效果。 希望大家学习愉快, 我们下次再见!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值