using UnityEngine;using System.Collections;using System;using System.Threading;using System.Net;using System.Net.Sockets;using System.IO;using mutils; using scopely.msgpacksharp;using structs; public class AsyncSocket{ //单例模式 private static AsyncSocket instance; public Socket clientSocket; public string host = ".0.0.1"; public int hostPort = ; public static AsyncSocket GetInstance () { if (instance == null) { instance = new AsyncSocket (); } return instance; } public AsyncSocket () { //创建Socket对象 clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //服务器IP地址 IPAddress ipAddress = IPAddress.Parse (host); //这是一个异步的建立连接,当连接建立成功时调用connectCallback方法 IAsyncResult result = clientSocket.BeginConnect (ipAddress, hostPort, new AsyncCallback (connectCallback), clientSocket); //当连接超过5秒还没成功表示超时,非必须 //这段succ变量,偶尔在Mono里报错,实在看不出问题,去掉也没问题// bool succ = result.AsyncWaitHandle.WaitOne ();// if (!succ) {// //超时// Debug.Log ("time out ");// closeSocket ();// } } private void sendCallback (IAsyncResult asyncConnect) { int bytesSent = clientSocket.EndSend (asyncConnect); Debug.Log ("sendCallback: sent" bytesSent); closeSocket (); } private void connectCallback (IAsyncResult asyncConnect) { Debug.Log ("EndConnect"); clientSocket.EndConnect (asyncConnect); businessComm (); } private void businessComm () { if (!clientSocket.Connected) { Debug.Log ("businessComm clientSocket.Connected false"); closeSocket (); } MemoryStream memStream = new MemoryStream (); memStream.Write (SocketUtils.IntToByte (), 0, 4); memStream.Write (SocketUtils.IntToByte (), 0, 4); MyMessage message = new MyMessage (); message.MyNumber = ; message.MyString = "abcde"; byte[] datas = MsgPackSerializer.SerializeObject (message); memStream.Write (SocketUtils.IntToByte (datas.Length), 0, 4); memStream.Write (datas, 0, datas.Length); byte[] byteData = memStream.GetBuffer (); clientSocket.BeginSend (byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback (sendCallback), clientSocket); } //关闭Socket public void closeSocket () { Debug.Log ("Socket Closed"); clientSocket.Close (); } }
推荐整理分享unity3d 异步socket packet序列化(unity socket udp),希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:unity的socket,unity socket udp,unity异步加载原理,unity异步执行,unity异步加载场景优化,unity异步执行,unity异步执行,unity异步加载原理,内容如对您有帮助,希望把文章链接给更多的朋友!
触发器调用:
?void OnTriggerEnter (Collider col) { if (col.gameObject.tag == "Player") { AsyncSocket.GetInstance (); } }
Unity3D游戏开发之回合制游戏原型的实现
Unity3D游戏开发之鼠标旋转、缩放实现3D物品展示
OnApplicationFocus 前两天用到ngui做拖拽效果,将一张图片拖拽到另一个固定的子里,看的是NGUI的一个demo做的,但是会有一个问题,就是在推拽过程中,如果切换应用程