Socket









How do I use Socket
Below are practical examples compiled from projects for learning and reference purposes

Featured Snippets


File name: PhotonEditor.cs Copy
241     internal protected static bool CheckPunPlus()
242     {
243         androidLibExists = File.Exists("Assets/Plugins/Android/libPhotonSocketPlugin.so");
244         iphoneLibExists = File.Exists("Assets/Plugins/IPhone/libPhotonSocketPlugin.a");
245
246         isPunPlus = androidLibExists || iphoneLibExists;
247         return isPunPlus;
248     }
File name: NetworkingPeer.cs Copy
185     public NetworkingPeer(IPhotonPeerListener listener, string playername, ConnectionProtocol connectionProtocol) : base(listener, connectionProtocol)
186     {
187         #if !UNITY_EDITOR && (UNITY_WINRT)
188         // this automatically uses a separate assembly-file with Win8-style Socket usage (not possible in Editor)
189         Debug.LogWarning("Using PingWindowsStore");
190         PhotonHandler.PingImplementation = typeof(PingWindowsStore); // but for ping, we have to set the implementation explicitly to Win 8 Store/Phone
191         #endif
192
193         #pragma warning disable 0162 // the library variant defines if we should use PUN's SocketUdp variant (at all)
194         if (PhotonPeer.NoSocket)
195         {
196             #if !UNITY_EDITOR && (UNITY_PS3 || UNITY_ANDROID)
197             Debug.Log("Using class SocketUdpNativeDynamic");
198             this.SocketImplementation = typeof(SocketUdpNativeDynamic);
199             PhotonHandler.PingImplementation = typeof(PingNativeDynamic);
200             #elif !UNITY_EDITOR && UNITY_IPHONE
201             Debug.Log("Using class SocketUdpNativeStatic");
202             this.SocketImplementation = typeof(SocketUdpNativeStatic);
203             PhotonHandler.PingImplementation = typeof(PingNativeStatic);
204             #elif !UNITY_EDITOR && (UNITY_WINRT)
205             // this automatically uses a separate assembly-file with Win8-style Socket usage (not possible in Editor)
206             #else
207             this.SocketImplementation = typeof (SocketUdp);
208             PhotonHandler.PingImplementation = typeof(PingMonoEditor);
209             #endif
210
211             if (this.SocketImplementation == null)
212             {
213                 Debug.Log("No socket implementation set for 'NoSocket' assembly. Please contact Exit Games.");
214             }
215         }
216         #pragma warning restore 0162
217
218         if (PhotonHandler.PingImplementation == null)
219         {
220             PhotonHandler.PingImplementation = typeof(PingMono);
221         }
222
223         this.Listener = this;
224         this.lobby = TypedLobby.Default;
225         this.LimitOfUnreliableCommands = 40;
226
227         // don't set the field directly! the listener is passed on to other classes, which get updated by the property set method
228         this.externalListener = listener;
229         this.PlayerName = playername;
230         this.mLocalActor = new PhotonPlayer(true, -1, this.playername);
231         this.AddNewPlayer(this.mLocalActor.ID, this.mLocalActor);
232
233         // RPC shortcut lookup creation (from list of RPCs, which is updated by Editor scripts)
234         rpcShortcuts = new Dictionary(PhotonNetwork.PhotonServerSettings.RpcList.Count);
235         for (int index = 0; index < PhotonNetwork.PhotonServerSettings.RpcList.Count; index++)
236         {
237             var name = PhotonNetwork.PhotonServerSettings.RpcList[index];
238             rpcShortcuts[name] = index;
239         }
240
241         this.State = global::PeerState.PeerCreated;
242     }
File name: PhotonHandler.cs Copy
232     internal IEnumerator PingAvailableRegionsCoroutine(bool connectToBest)
233     {
234         BestRegionCodeCurrently = CloudRegionCode.none;
235         while (PhotonNetwork.networkingPeer.AvailableRegions == null)
236         {
237             if (PhotonNetwork.connectionStateDetailed != PeerState.ConnectingToNameServer && PhotonNetwork.connectionStateDetailed != PeerState.ConnectedToNameServer)
238             {
239                 Debug.LogError("Call ConnectToNameServer to ping available regions.");
240                 yield break; // break if we don't connect to the nameserver at all
241             }
242
243             Debug.Log("Waiting for AvailableRegions. State: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.Server + " PhotonNetwork.networkingPeer.AvailableRegions " + (PhotonNetwork.networkingPeer.AvailableRegions != null));
244             yield return new WaitForSeconds(0.25f); // wait until pinging finished (offline mode won't ping)
245         }
246
247         if (PhotonNetwork.networkingPeer.AvailableRegions == null || PhotonNetwork.networkingPeer.AvailableRegions.Count == 0)
248         {
249             Debug.LogError("No regions available. Are you sure your appid is valid and setup?");
250             yield break; // break if we don't get regions at all
251         }
252
253         //#if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IPHONE)
254         //#pragma warning disable 0162 // the library variant defines if we should use PUN's SocketUdp variant (at all)
255         //if (PhotonPeer.NoSocket)
256         //{
257         // if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
258         // {
259         // Debug.Log("PUN disconnects to re-use native sockets for pining servers and to find the best.");
260         // }
261         // PhotonNetwork.Disconnect();
262         //}
263         //#pragma warning restore 0162
264         //#endif
265
266         PhotonPingManager pingManager = new PhotonPingManager();
267         foreach (Region region in PhotonNetwork.networkingPeer.AvailableRegions)
268         {
269             SP.StartCoroutine(pingManager.PingSocket(region));
270         }
271
272         while (!pingManager.Done)
273         {
274             yield return new WaitForSeconds(0.1f); // wait until pinging finished (offline mode won't ping)
275         }
276
277
278         Region best = pingManager.BestRegion;
279         PhotonHandler.BestRegionCodeCurrently = best.Code;
280         PhotonHandler.BestRegionCodeInPreferences = best.Code;
281
282         Debug.Log("Found best region: " + best.Code + " ping: " + best.Ping + ". Calling ConnectToRegionMaster() is: " + connectToBest);
283
284
285         if (connectToBest)
286         {
287             PhotonNetwork.networkingPeer.ConnectToRegionMaster(best.Code);
288         }
289     }
File name: PingCloudRegions.cs Copy
43     public override bool Done()
44     {
45         if (this.GotResult || sock == null)
46         {
47             return true;
48         }
49
50         if (sock.Available <= 0)
51         {
52             return false;
53         }
54
55         int read = sock.Receive(PingBytes, SocketFlags.None);
56         //Debug.Log("Got: " + SupportClass.ByteArrayToString(PingBytes));
57         bool replyMatch = PingBytes[PingBytes.Length - 1] == PingId && read == PingLength;
58         if (!replyMatch) Debug.Log("ReplyMatch is false! ");
59
60
61         this.Successful = read == PingBytes.Length && PingBytes[PingBytes.Length - 1] == PingId;
62         this.GotResult = true;
63         return true;
64     }
File name: PingCloudRegions.cs Copy
118     public IEnumerator PingSocket(Region region)
119     {
120         region.Ping = Attempts*MaxMilliseconsPerPing;
121
122         this.PingsRunning++; // TODO: Add try-catch to make sure the PingsRunning are reduced at the end and that the lib does not crash the app
123         PhotonPing ping;
124         //Debug.Log("PhotonHandler.PingImplementation " + PhotonHandler.PingImplementation);
125         if (PhotonHandler.PingImplementation == typeof(PingNativeDynamic))
126         {
127             Debug.Log("Using constructor for new PingNativeDynamic()"); // it seems on android, the Activator can't find the default Constructor
128             ping = new PingNativeDynamic();
129         }
130         else
131         {
132             ping = (PhotonPing)Activator.CreateInstance(PhotonHandler.PingImplementation);
133         }
134
135         //Debug.Log("Ping is: " + ping + " type " + ping.GetType());
136
137         float rttSum = 0.0f;
138         int replyCount = 0;
139
140
141         // PhotonPing.StartPing() requires a plain IP address without port (on all but Windows 8 platforms).
142         // So: remove port and do the DNS-resolving if needed
143         string cleanIpOfRegion = region.HostAndPort;
144         int indexOfColon = cleanIpOfRegion.LastIndexOf(':');
145         if (indexOfColon > 1)
146         {
147             cleanIpOfRegion = cleanIpOfRegion.Substring(0, indexOfColon);
148         }
149         cleanIpOfRegion = ResolveHost(cleanIpOfRegion);
150         //Debug.Log("Resolved and port-less IP is: " + cleanIpOfRegion);
151
152
153         for (int i = 0; i < Attempts; i++)
154         {
155             bool overtime = false;
156             Stopwatch sw = new Stopwatch();
157             sw.Start();
158
159             try
160             {
161                 ping.StartPing(cleanIpOfRegion);
162             }
163             catch (Exception e)
164             {
165                 Debug.Log("catched: " + e);
166                 this.PingsRunning--;
167                 break;
168             }
169
170
171             while (!ping.Done())
172             {
173                 if (sw.ElapsedMilliseconds >= MaxMilliseconsPerPing)
174                 {
175                     overtime = true;
176                     break;
177                 }
178                 yield return 0; // keep this loop tight, to avoid adding local lag to rtt.
179             }
180             int rtt = (int)sw.ElapsedMilliseconds;
181
182
183             if (IgnoreInitialAttempt && i == 0)
184             {
185                 // do nothing.
186             }
187             else if (ping.Successful && !overtime)
188             {
189                 rttSum += rtt;
190                 replyCount++;
191                 region.Ping = (int)((rttSum) / replyCount);
192                 //Debug.Log("region " + region.Code + " RTT " + region.Ping + " success: " + ping.Successful + " over: " + overtime);
193             }
194
195             yield return new WaitForSeconds(0.1f);
196         }
197
198         this.PingsRunning--;
199
200         //Debug.Log("this.PingsRunning: " + this.PingsRunning + " this debug: " + ping.DebugString);
201         yield return null;
202     }
File name: SocketUdp.cs Copy
28         public SocketUdp(PeerBase npeer) : base(npeer)
29         {
30             if (this.ReportDebugOfLevel(DebugLevel.ALL))
31             {
32                 this.Listener.DebugReturn(DebugLevel.ALL, "CSharpSocket: UDP, Unity3d.");
33             }
34
35             this.Protocol = ConnectionProtocol.Udp;
36             this.PollReceive = false;
37         }
File name: SocketUdp.cs Copy
39         public override bool Connect()
40         {
41             lock (this.syncer)
42             {
43                 bool baseOk = base.Connect();
44                 if (!baseOk)
45                 {
46                     return false;
47                 }
48
49                 this.State = PhotonSocketState.Connecting;
50
51                 Thread dns = new Thread(this.DnsAndConnect);
52                 dns.Name = "photon dns thread";
53                 dns.IsBackground = true;
54                 dns.Start();
55
56                 return true;
57             }
58         }
File name: SocketUdp.cs Copy
60         public override bool Disconnect()
61         {
62             if (this.ReportDebugOfLevel(DebugLevel.INFO))
63             {
64                 this.EnqueueDebugReturn(DebugLevel.INFO, "CSharpSocket.Disconnect()");
65             }
66
67             this.State = PhotonSocketState.Disconnecting;
68
69             lock (this.syncer)
70             {
71                 if (this.sock != null)
72                 {
73                     try
74                     {
75                         this.sock.Close();
76                     }
77                     catch (Exception ex)
78                     {
79                         this.EnqueueDebugReturn(DebugLevel.INFO, "Exception in Disconnect(): " + ex);
80                     }
81
82                     this.sock = null;
83                 }
84             }
85
86             this.State = PhotonSocketState.Disconnected;
87             return true;
88         }
File name: SocketUdp.cs Copy
91         public override PhotonSocketError Send(byte[] data, int length)
92         {
93             lock (this.syncer)
94             {
95                 if (!this.sock.Connected)
96                 {
97                     return PhotonSocketError.Skipped;
98                 }
99
100                 try
101                 {
102                     sock.Send(data, 0, length, SocketFlags.None);
103                 }
104                 catch
105                 {
106                     return PhotonSocketError.Exception;
107                 }
108             }
109
110             return PhotonSocketError.Success;
111         }
File name: SocketUdp.cs Copy
113         public override PhotonSocketError Receive(out byte[] data)
114         {
115             data = null;
116             return PhotonSocketError.NoData;
117         }

Download file with original file name:Socket

Socket 127 lượt xem

Gõ tìm kiếm nhanh...