Advertisement
Guest User

Untitled

a guest
Sep 11th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.75 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10.  
  11. /// <summary>
  12. /// UDP client component.
  13. /// </summary>
  14. namespace UDPClientModule
  15. {
  16.     public class UDPClientComponent : MonoBehaviour {
  17.  
  18.         private string  serverURL;
  19.  
  20.         private int serverPort;
  21.        
  22.         int clientPort;
  23.  
  24.         private UdpClient udpClient;
  25.  
  26.         private readonly object udpClientLock = new object();
  27.  
  28.         static private readonly char[] Delimiter = new char[] {','};
  29.  
  30.         string receivedMsg = string.Empty;
  31.  
  32.         private Dictionary<string, List<Action<SocketUDPEvent>>> handlers;
  33.  
  34.         private Queue<SocketUDPEvent> eventQueue;
  35.  
  36.         private object eventQueueLock;
  37.  
  38.         private IPEndPoint endPoint;
  39.  
  40.         private string listenerInput = string.Empty;
  41.  
  42.         public enum UDPSocketState {DISCONNECTED,CONNECTED,ERROR,SENDING_MESSAGE};
  43.  
  44.         public UDPSocketState udpSocketState;
  45.  
  46.         private Thread tListenner;
  47.  
  48.         public string serverIP = string.Empty;
  49.  
  50.         public bool noNetwork;
  51.  
  52.         public string localNetworkIP;
  53.  
  54.  
  55.         public void Awake()
  56.         {
  57.             handlers = new Dictionary<string, List<Action<SocketUDPEvent>>>();
  58.  
  59.             eventQueueLock = new object();
  60.  
  61.             eventQueue = new Queue<SocketUDPEvent>();
  62.  
  63.    
  64.             udpSocketState = UDPSocketState.DISCONNECTED;
  65.         }
  66.  
  67.  
  68.  
  69.  
  70.         /// <summary>
  71.         /// open a connection with the specific server using the server URL (IP) and server Port.
  72.         /// </summary>
  73.         /// <param name="_serverURL">Server IP.</param>
  74.         /// <param name="_serverPort">Server port.</param>
  75.         /// <param name="_clientPort">Client port.</param>
  76.         public void connect(string _serverURL, int _serverPort, int _clientPort) {
  77.  
  78.         //  Debug.Log ("tentando estabelecer conexão com o servidor");
  79.             if ( tListenner != null && tListenner.IsAlive) {
  80.                
  81.                 disconnect();
  82.  
  83.                 while (tListenner != null && tListenner.IsAlive) {
  84.  
  85.  
  86.                 }
  87.             }
  88.  
  89.             //host udp server
  90.             this.serverURL = _serverURL;
  91.  
  92.             //server port
  93.             this.serverPort = _serverPort;
  94.  
  95.             //client port
  96.             this.clientPort = _clientPort;
  97.            
  98.             // start  listener thread
  99.             tListenner = new Thread(
  100.                 new ThreadStart(OnListeningServer));
  101.            
  102.             tListenner.IsBackground = true;
  103.  
  104.             tListenner.Start();
  105.  
  106.  
  107.  
  108.         }
  109.  
  110.  
  111.         public void  OnListeningServer()
  112.         {
  113.  
  114.             try
  115.             {
  116.                
  117.                 lock ( udpClientLock) {
  118.                    
  119.                     udpClient = new UdpClient ();
  120.  
  121.                     udpClient.ExclusiveAddressUse = false;
  122.  
  123.                     udpClient.Client.SetSocketOption(
  124.                         SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  125.  
  126.                     IPEndPoint localEp = new IPEndPoint(IPAddress.Any,clientPort);
  127.  
  128.                     udpClient.Client.Bind(localEp);
  129.  
  130.                     udpSocketState = UDPSocketState.CONNECTED;
  131.  
  132.                     udpClient.BeginReceive (new AsyncCallback (OnWaitPacketsCallback), null);
  133.  
  134.  
  135.                 }
  136.  
  137.             }
  138.             catch
  139.             {
  140.                
  141.                 throw;
  142.             }
  143.         }
  144.  
  145.  
  146.  
  147.         public void OnWaitPacketsCallback(IAsyncResult res)
  148.         {
  149.  
  150.             lock (udpClientLock) {
  151.  
  152.                 byte[] recPacket = udpClient.EndReceive (res, ref endPoint);
  153.                 MessageReceived(recPacket, endPoint.Address.ToString(), endPoint.Port);
  154.  
  155.                 if (recPacket != null && recPacket.Length > 0) {
  156.                     lock (eventQueueLock) {
  157.  
  158.                         //decode the received bytes vector in string fotmat
  159.                         //receivedMsg = "callback_name,param 1,param 2,param n, etc."
  160.                         receivedMsg = Encoding.UTF8.GetString (recPacket);
  161.  
  162.                         //separates the items contained in the package using the comma "," as sifter
  163.                         //and it puts them separately in the vector package []
  164.                         /*
  165.                           * package[0]= callback_name: e.g.: "PONG"
  166.                           * package[1]= message: e.g.: "pong!!!"
  167.                           * package[2]=  other message for example!
  168.                         */
  169.  
  170.                         var package = receivedMsg.Split (Delimiter);
  171.  
  172.                         //enqueue
  173.                         eventQueue.Enqueue(new SocketUDPEvent(package [0], receivedMsg));
  174.  
  175.                         receivedMsg = string.Empty;
  176.                     }//END_LOCK
  177.                 }//END_IF
  178.                    
  179.                 udpClient.BeginReceive (new AsyncCallback (OnWaitPacketsCallback), null);
  180.  
  181.             }//END_LOCK
  182.         }
  183.  
  184.  
  185.         private void InvokEvent(SocketUDPEvent ev)
  186.         {
  187.  
  188.             if (!handlers.ContainsKey(ev.name)) { return; }
  189.  
  190.             foreach (Action<SocketUDPEvent> handler in this.handlers[ev.name]) {
  191.                
  192.                 try{
  193.  
  194.                     handler(ev);
  195.                    }
  196.                 catch(Exception ex){}
  197.             }
  198.         }
  199.  
  200.  
  201.         public void MessageReceived(byte[] data, string ipHost, int portHost)
  202.         {
  203.  
  204.             //Debug.Log(string.Format("Received data:: {0} of IP:: {1} and Port:: {2}", Encoding.UTF8.GetString (data), ipHost, portHost));
  205.  
  206.         }
  207.  
  208.         /// <summary>
  209.         /// listening server messages.
  210.         /// </summary>
  211.         /// <param name="ev">Callback name</param>
  212.         /// <param name="callback">Callback function.</param>
  213.         public void On(string ev, Action<SocketUDPEvent> callback)
  214.         {
  215.             if (!handlers.ContainsKey(ev)) {
  216.                
  217.                 handlers[ev] = new List<Action<SocketUDPEvent>>();
  218.             }
  219.  
  220.             handlers[ev].Add(callback);
  221.         }
  222.  
  223.         /// <summary>
  224.         /// Emit the pack or message to server.
  225.         /// </summary>
  226.         /// <param name="callbackID">Callback ID.</param>
  227.         /// <param name="_pack">message</param>
  228.         public void Emit(string callbackID, string _pack)
  229.         {
  230.  
  231.             try{
  232.  
  233.                 if(udpSocketState == UDPSocketState.CONNECTED)
  234.                 {
  235.                     lock ( udpClientLock) {
  236.                        
  237.                         if(udpClient == null)
  238.                         {
  239.                             udpClient = new UdpClient ();
  240.  
  241.                             udpClient.ExclusiveAddressUse = false;
  242.  
  243.                             udpClient.Client.SetSocketOption(
  244.                                 SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  245.  
  246.                             IPEndPoint localEp = new IPEndPoint(IPAddress.Any, clientPort);
  247.  
  248.                             udpClient.Client.Bind(localEp);
  249.                         }
  250.  
  251.  
  252.                         udpSocketState = UDPSocketState.SENDING_MESSAGE;
  253.  
  254.                         string new_pack = callbackID+","+_pack;
  255.  
  256.                         byte[] data = Encoding.UTF8.GetBytes (new_pack.ToString ()); //convert to bytes
  257.  
  258.                         var endPoint = new IPEndPoint(IPAddress.Parse(serverURL), serverPort);
  259.  
  260.                         udpClient.Send(data, data.Length,endPoint );
  261.  
  262.                         udpSocketState = UDPSocketState.CONNECTED;
  263.                     }
  264.                 }
  265.             }
  266.             catch(Exception e) {
  267.                 listenerInput = e.InnerException.Message;
  268.             }
  269.         }
  270.  
  271.  
  272.         //get local server ip address
  273.         public string GetServerIP() {
  274.  
  275.             serverIP = string.Empty;
  276.  
  277.             string address =  string.Empty;
  278.  
  279.             string subAddress = string.Empty;
  280.  
  281.                
  282.                
  283.                 foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces()) {
  284.                    if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
  285.                         netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {
  286.                    foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses) {
  287.             if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork) {
  288.                 address = addrInfo.Address;
  289.  
  290.                
  291.             }
  292.         }
  293.     }  
  294. }
  295.  
  296.             if (address == string.Empty)
  297.             {
  298.                
  299.                 noNetwork = true;
  300.  
  301.                 return string.Empty;
  302.             }
  303.             else
  304.             {
  305.                 noNetwork = false;
  306.  
  307.                 subAddress = address.Remove(address.LastIndexOf('.'));
  308.  
  309.                 serverIP = subAddress + "." + 255;
  310.  
  311.                 return subAddress + "." + 255;
  312.             }
  313.             return string.Empty;
  314.  
  315.  
  316.         }
  317.  
  318.  
  319.  
  320.  
  321.  
  322.         private void OnDestroy() {
  323.            
  324.             disconnect ();
  325.         }
  326.  
  327.         public void Update()
  328.         {
  329.             lock(eventQueueLock){
  330.                
  331.                 while(eventQueue.Count > 0)
  332.                 {
  333.  
  334.                     InvokEvent(eventQueue.Dequeue());
  335.                 }
  336.             }
  337.  
  338.  
  339.  
  340.  
  341.         }
  342.  
  343.         void OnApplicationQuit() {
  344.  
  345.             disconnect ();
  346.  
  347.         }
  348.  
  349.         /// <summary>
  350.         /// Disconnect this client.
  351.         /// </summary>
  352.         public void disconnect() {
  353.  
  354.  
  355.             lock (udpClientLock) {
  356.                
  357.                 if (udpClient != null) {
  358.                    
  359.                     udpClient.Close();
  360.  
  361.                     udpClient = null;
  362.                 }
  363.  
  364.             }//END_LOCK
  365.  
  366.             if (tListenner!=null) {
  367.                
  368.                 tListenner.Abort ();
  369.             }
  370.  
  371.         }
  372.  
  373.  
  374.     }
  375. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement