Просмотр исходного кода

demo使用websocket成功运行,测试方法:
1.服务端启动配置使用LocalServerWebsocket.txt,
2.NetOuterComponent.cs协议改成Websocket
3.Unity菜单tools全局配置改成ws://127.0.0.1:8080

tanghai 7 лет назад
Родитель
Сommit
9977409245

+ 6 - 0
Server/Model/Server.Model.csproj

@@ -23,6 +23,12 @@
     <Compile Include="..\..\Unity\Assets\Scripts\Module\Message\NetOuterComponent.cs">
       <Link>Module\Message\NetOuterComponent.cs</Link>
     </Compile>
+    <Compile Include="..\..\Unity\Assets\Scripts\Module\Message\Network\WebSocket\WChannel.cs">
+      <Link>Module\Message\Network\WebSocket\WChannel.cs</Link>
+    </Compile>
+    <Compile Include="..\..\Unity\Assets\Scripts\Module\Message\Network\WebSocket\WService.cs">
+      <Link>Module\Message\Network\WebSocket\WService.cs</Link>
+    </Compile>
     <Compile Include="..\..\Unity\Hotfix\Module\Message\MessagePool.cs">
       <Link>Module\Message\MessagePool\ETHotfix\MessagePool.cs</Link>
     </Compile>

+ 2 - 1
Unity/Assets/Scripts/Module/Message/Network/KCP/KService.cs

@@ -298,7 +298,8 @@ namespace ETModel
 
 		public override AChannel ConnectChannel(string address)
 		{
-			throw new NotImplementedException();
+			IPEndPoint ipEndPoint2 = NetworkHelper.ToIPEndPoint(address);
+			return this.ConnectChannel(ipEndPoint2);
 		}
 
 		public override void Remove(long id)

+ 2 - 1
Unity/Assets/Scripts/Module/Message/Network/TCP/TService.cs

@@ -131,7 +131,8 @@ namespace ETModel
 
 		public override AChannel ConnectChannel(string address)
 		{
-			throw new NotImplementedException();
+			IPEndPoint ipEndPoint = NetworkHelper.ToIPEndPoint(address);
+			return this.ConnectChannel(ipEndPoint);
 		}
 
 		public override void Remove(long id)

+ 8 - 0
Unity/Assets/Scripts/Module/Message/Network/WebSocket.meta

@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 02cb26b1214c31847af71b0796e90476
+folderAsset: yes
+DefaultImporter:
+  externalObjects: {}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 30 - 9
Server/Model/Module/Message/Network/WebSocket/WChannel.cs → Unity/Assets/Scripts/Module/Message/Network/WebSocket/WChannel.cs

@@ -19,6 +19,8 @@ namespace ETModel
         private bool isConnected;
 
         private readonly MemoryStream memoryStream;
+
+        private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
         
         public WChannel(HttpListenerWebSocketContext webSocketContext, AService service): base(service, ChannelType.Accept)
         {
@@ -50,8 +52,13 @@ namespace ETModel
             {
                 return;
             }
+            
             base.Dispose();
             
+            this.cancellationTokenSource.Cancel();
+            this.cancellationTokenSource.Dispose();
+            this.cancellationTokenSource = null;
+            
             this.webSocket.Dispose();
             
             this.memoryStream.Dispose();
@@ -84,7 +91,7 @@ namespace ETModel
         {
             try
             {
-                await ((ClientWebSocket)this.webSocket).ConnectAsync(new Uri(url), new CancellationToken());
+                await ((ClientWebSocket)this.webSocket).ConnectAsync(new Uri(url), cancellationTokenSource.Token);
                 isConnected = true;
                 this.Start();
             }
@@ -109,6 +116,10 @@ namespace ETModel
 
         public async void StartSend()
         {
+            if (this.IsDisposed)
+            {
+                return;
+            }
             try
             {
                 if (this.isSending)
@@ -129,7 +140,11 @@ namespace ETModel
                     byte[] bytes = this.queue.Dequeue();
                     try
                     {
-                        await this.webSocket.SendAsync(new ReadOnlyMemory<byte>(bytes, 0, bytes.Length), WebSocketMessageType.Binary, true, new CancellationToken());
+                        await this.webSocket.SendAsync(new ArraySegment<byte>(bytes, 0, bytes.Length), WebSocketMessageType.Binary, true, cancellationTokenSource.Token);
+                        if (this.IsDisposed)
+                        {
+                            return;
+                        }
                     }
                     catch (Exception e)
                     {
@@ -147,14 +162,21 @@ namespace ETModel
 
         public async void StartRecv()
         {
+            if (this.IsDisposed)
+            {
+                return;
+            }
             try
             {
                 while (true)
                 {
-                    ValueWebSocketReceiveResult receiveResult;
                     try
                     {
-                        receiveResult = await this.webSocket.ReceiveAsync(new Memory<byte>(this.Stream.GetBuffer(), 0, this.Stream.Capacity), new CancellationToken());
+                        var receiveResult = await this.webSocket.ReceiveAsync(new ArraySegment<byte>(this.Stream.GetBuffer(), 0, this.Stream.Capacity), cancellationTokenSource.Token);
+                        if (this.IsDisposed)
+                        {
+                            return;
+                        }
                         if (receiveResult.MessageType == WebSocketMessageType.Close)
                         {
                             this.OnError(ErrorCode.ERR_WebsocketPeerReset);
@@ -163,20 +185,19 @@ namespace ETModel
 
                         if (receiveResult.Count > ushort.MaxValue)
                         {
-                            await this.webSocket.CloseAsync(WebSocketCloseStatus.MessageTooBig, $"message too big: {receiveResult.Count}", new CancellationToken());
+                            await this.webSocket.CloseAsync(WebSocketCloseStatus.MessageTooBig, $"message too big: {receiveResult.Count}", cancellationTokenSource.Token);
                             this.OnError(ErrorCode.ERR_WebsocketMessageTooBig);
                             return;
                         }
+                        
+                        this.Stream.SetLength(receiveResult.Count);
+                        this.OnRead(this.Stream);
                     }
                     catch (Exception e)
                     {
-                        Log.Error(e);
                         this.OnError(ErrorCode.ERR_WebsocketRecvError);
                         return;
                     }
-                
-                    this.Stream.SetLength(receiveResult.Count);
-                    this.OnRead(this.Stream);
                 }
             }
             catch (Exception e)

+ 11 - 0
Unity/Assets/Scripts/Module/Message/Network/WebSocket/WChannel.cs.meta

@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8e9431d46e7e100479fce069d4c08079
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 0 - 0
Server/Model/Module/Message/Network/WebSocket/WService.cs → Unity/Assets/Scripts/Module/Message/Network/WebSocket/WService.cs


+ 11 - 0
Unity/Assets/Scripts/Module/Message/Network/WebSocket/WService.cs.meta

@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ab08a203cf5da164c86fbc14d09e3a3b
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 2 - 6
Unity/Assets/Scripts/Module/Message/NetworkComponent.cs

@@ -29,11 +29,9 @@ namespace ETModel
 					case NetworkProtocol.TCP:
 						this.Service = new TService();
 						break;
-#if SERVER
 					case NetworkProtocol.WebSocket:
 						this.Service = new WService();
 						break;
-#endif
 				}
 			}
 			catch (Exception e)
@@ -57,12 +55,10 @@ namespace ETModel
 						ipEndPoint = NetworkHelper.ToIPEndPoint(address);
 						this.Service = new TService(ipEndPoint, this.OnAccept);
 						break;
-#if SERVER
 					case NetworkProtocol.WebSocket:
 						string[] prefixs = address.Split(';');
 						this.Service = new WService(prefixs, this.OnAccept);
 						break;
-#endif
 				}
 			}
 			catch (Exception e)
@@ -114,9 +110,9 @@ namespace ETModel
 		/// <summary>
 		/// 创建一个新Session
 		/// </summary>
-		public Session Create(string url)
+		public Session Create(string address)
 		{
-			AChannel channel = this.Service.ConnectChannel(url);
+			AChannel channel = this.Service.ConnectChannel(address);
 			Session session = ComponentFactory.CreateWithParent<Session, AChannel>(this, channel);
 			this.sessions.Add(session.Id, session);
 			return session;

+ 3 - 5
Unity/Hotfix/UI/UILogin/Component/UILoginComponent.cs

@@ -32,20 +32,18 @@ namespace ETHotfix
 		{
 			try
 			{
-				IPEndPoint connetEndPoint = NetworkHelper.ToIPEndPoint(GlobalConfigComponent.Instance.GlobalProto.Address);
-
 				string text = this.account.GetComponent<InputField>().text;
 
 				// 创建一个ETModel层的Session
-				ETModel.Session session = ETModel.Game.Scene.GetComponent<NetOuterComponent>().Create(connetEndPoint);
+				ETModel.Session session = ETModel.Game.Scene.GetComponent<NetOuterComponent>().Create(GlobalConfigComponent.Instance.GlobalProto.Address);
+				
 				// 创建一个ETHotfix层的Session, ETHotfix的Session会通过ETModel层的Session发送消息
 				Session realmSession = ComponentFactory.Create<Session, ETModel.Session>(session);
 				R2C_Login r2CLogin = (R2C_Login) await realmSession.Call(new C2R_Login() { Account = text, Password = "111111" });
 				realmSession.Dispose();
 
-				connetEndPoint = NetworkHelper.ToIPEndPoint(r2CLogin.Address);
 				// 创建一个ETModel层的Session,并且保存到ETModel.SessionComponent中
-				ETModel.Session gateSession = ETModel.Game.Scene.GetComponent<NetOuterComponent>().Create(connetEndPoint);
+				ETModel.Session gateSession = ETModel.Game.Scene.GetComponent<NetOuterComponent>().Create(r2CLogin.Address);
 				ETModel.Game.Scene.AddComponent<ETModel.SessionComponent>().Session = gateSession;
 				
 				// 创建一个ETHotfix层的Session, 并且保存到ETHotfix.SessionComponent中

+ 2 - 0
Unity/Unity.csproj

@@ -381,6 +381,8 @@
     <Compile Include="Assets\Scripts\Module\FrameSync\UnitComponent.cs" />
     <Compile Include="Assets\Scripts\Module\FrameSync\UnitFactory.cs" />
     <Compile Include="Assets\Scripts\Module\Message\AMHandler.cs" />
+    <Compile Include="Assets\Scripts\Module\Message\Network\WebSocket\WChannel.cs" />
+    <Compile Include="Assets\Scripts\Module\Message\Network\WebSocket\WService.cs" />
     <Compile Include="Assets\Scripts\Module\Message\OuterMessageDispatcher.cs" />
     <Compile Include="Assets\Scripts\Module\Message\ErrorCode.cs" />
     <Compile Include="Assets\Scripts\Module\Message\IActorMessage.cs" />