Advertisement
Guest User

udp

a guest
May 20th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.37 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using System.Net.Sockets;
  4. using System.Net;
  5. using System;
  6. using System.Text;
  7.  
  8. public class MinimalNet : MonoBehaviour
  9. {
  10.  
  11.     public bool isHost, isOnline;
  12.  
  13.     public List<IPEndPoint> clients;
  14.  
  15.     IPEndPoint ownPoint, hostPoint, broadPoint;
  16.     public string ownAddr;
  17.     public int ownPort = 35000, hostPort;
  18.  
  19.     public string hostAddr;
  20.  
  21.     public List<string> lastReceivedMSGs;
  22.  
  23.     UdpClient udp;
  24.  
  25.     string message;
  26.  
  27.     byte[] sendBuff, recvBuff;
  28.  
  29.     object hostLock;
  30.  
  31.     private void Start() {
  32.         GetOwnAddr();
  33.         hostAddr = ownAddr;
  34.         hostPort = ownPort;
  35.         sendBuff = new byte[128];
  36.         recvBuff = new byte[128];
  37.  
  38.         hostLock = new object();
  39.         lastReceivedMSGs = new List<string>();
  40.     }
  41.  
  42.     void ClearData() {
  43.         if ( clients == null ) clients = new List<IPEndPoint>(); else clients.Clear();
  44.     }
  45.  
  46.     private void OnGUI() {
  47.         GUILayout.BeginHorizontal();
  48.         GUILayout.Label( "Own Port" );
  49.         string port = GUILayout.TextField( ownPort.ToString() );
  50.         int.TryParse( port, out ownPort );
  51.         GUILayout.EndHorizontal();
  52.  
  53.         if ( !isHost ) {
  54.             GUILayout.BeginHorizontal();
  55.             GUILayout.Label( "Host Address" );
  56.             hostAddr = GUILayout.TextField( hostAddr );
  57.             GUILayout.EndHorizontal();
  58.  
  59.             GUILayout.BeginHorizontal();
  60.             GUILayout.Label( "Host Port" );
  61.             string hPort = GUILayout.TextField( hostPort.ToString() );
  62.             int.TryParse( hPort, out hostPort );
  63.             GUILayout.EndHorizontal();
  64.         }
  65.  
  66.         GUILayout.Box( string.Format( "Own Address: {0}:{1}", ownAddr, ownPort ) );
  67.         GUILayout.Box( string.Format( "Online: {0}   Host: {1}", isOnline, isHost ) );
  68.         if (!isOnline && GUILayout.Button( isHost ? "Become Client" : "Become Host")) { ToggleHost(); }
  69.         GUILayout.Space( 30 );
  70.         if ( GUILayout.Button( isOnline ? "Stop Online!" : "Go Online!" ) ) { ToggleOnline(); }
  71.         GUILayout.Space( 30 );
  72.  
  73.         GUILayout.BeginHorizontal();
  74.         message = GUILayout.TextField(message); if (GUILayout.Button("Send")) { SendUDPMessage( message ); message = ""; } if (isHost && isOnline && GUILayout.Button("Ping Broad")) { PingBroad(); }
  75.         GUILayout.EndHorizontal();
  76.         GUILayout.Space( 20 );
  77.         string chat = "";
  78.         for (int i = 0; i < lastReceivedMSGs.Count; i++ ) {
  79.             chat += string.Format("{0}\n", lastReceivedMSGs[i]);
  80.         }
  81.         GUILayout.Box( chat );
  82.     }
  83.  
  84.     //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  85.  
  86.     void StartUDP(int port) {
  87.         GetOwnAddr();
  88.         hostPoint = new IPEndPoint( IPAddress.Parse( hostAddr ), hostPort );
  89.         broadPoint = new IPEndPoint( IPAddress.Parse( "192.168.255.255" ), hostPort );
  90.         udp = new UdpClient(port);
  91.  
  92.         lastReceivedMSGs.Add( "Started UDP: " + ownAddr + ":" + port );
  93.         udp.BeginReceive( isHost ? new AsyncCallback( ReceiveAsHost ) : new AsyncCallback( ReceiveAsClient ), udp );
  94.     }
  95.  
  96.     void ToggleOnline() {
  97.         isOnline = !isOnline;
  98.         ClearData();
  99.  
  100.         if (isOnline) {
  101.             StartUDP( ownPort );
  102.         } else {
  103.             if (udp != null) udp.Close();
  104.         }
  105.  
  106.     }
  107.  
  108.     IPEndPoint sender;
  109.  
  110.     void ReceiveAsHost( IAsyncResult ar ) {
  111.         lock ( hostLock ) {
  112.             try {
  113.                 recvBuff = udp.EndReceive( ar, ref sender );
  114.  
  115.                 if ( !sender.Address.Equals( ownPoint.Address ) || sender.Port != ownPort) {
  116.                     if ( !clients.Contains( sender ) ) {
  117.                         clients.Add( sender );
  118.                         lastReceivedMSGs.Add( "Added Client: " + sender.Address + ":" + sender.Port );
  119.                     }
  120.  
  121.                     lastReceivedMSGs.Add( "Recv: " + Encoding.Unicode.GetString( recvBuff ) );
  122.                 }
  123.  
  124.             } catch ( Exception e ) {
  125.                 Debug.LogWarning( e.Message );
  126.             }
  127.         }
  128.  
  129.         udp.BeginReceive( new AsyncCallback( ReceiveAsHost ), udp );
  130.     }
  131.  
  132.     void ReceiveAsClient( IAsyncResult ar ) {
  133.         try {
  134.             recvBuff = udp.EndReceive( ar, ref sender );
  135.             lastReceivedMSGs.Add( "Recv: " + Encoding.Unicode.GetString( recvBuff ) );
  136.         } catch (Exception e) {
  137.             Debug.LogWarning( e.Message );
  138.         }
  139.  
  140.         udp.BeginReceive( new AsyncCallback( ReceiveAsClient ), udp );
  141.     }
  142.  
  143.     void SendUDPMessage( string txt ) {
  144.         if ( !isOnline ) return;
  145.  
  146.         txt = string.Format( "{0:0.000}: {1}", Time.timeSinceLevelLoad, txt );
  147.  
  148.         sendBuff = Encoding.Unicode.GetBytes( txt );
  149.  
  150.         if (isHost) {
  151.             for (int i = 0; i < clients.Count; i++ ) {
  152.                 udp.Send( sendBuff, sendBuff.Length, clients[i] );
  153.             }
  154.         } else {
  155.             udp.Send( sendBuff, sendBuff.Length, hostPoint );
  156.             txt += " to " + hostPoint.Address;
  157.         }
  158.  
  159.         lastReceivedMSGs.Add( txt );
  160.     }
  161.  
  162.     void PingBroad() {
  163.         sendBuff = Encoding.Unicode.GetBytes( string.Format( "{0:0.000}: {1}", Time.timeSinceLevelLoad, "PING!" ) );
  164.         udp.Send( sendBuff, sendBuff.Length, broadPoint );
  165.     }
  166.  
  167.     //----------------------------------------------------------------------------------------------------------------
  168.  
  169.     void ToggleHost() {
  170.         isHost = !isHost;
  171.         ClearData();
  172.     }
  173.  
  174.     void GetOwnAddr() {
  175.         string hostName = Dns.GetHostName();
  176.         IPHostEntry hostEn = Dns.GetHostEntry(hostName);
  177.  
  178.         ownPoint = null;
  179.  
  180.         for ( int i = 0; i < hostEn.AddressList.Length; i++ ) {
  181.  
  182.             if ( hostEn.AddressList[i].AddressFamily == AddressFamily.InterNetwork ) {
  183.                 print( hostEn.AddressList[i].ToString() );
  184.             }
  185.         }
  186.  
  187.         for ( int i = hostEn.AddressList.Length - 1; i >= 0; i-- ) {
  188.             if ( hostEn.AddressList[i].AddressFamily == AddressFamily.InterNetwork ) {
  189.                 ownPoint = new IPEndPoint( hostEn.AddressList[i], ownPort );
  190.                 break;
  191.             }
  192.         }
  193.        
  194.  
  195.         if (ownPoint != null) {
  196.             ownAddr = ownPoint.Address.ToString();
  197.         }
  198.  
  199.     }
  200.  
  201.     private void Update() {
  202.         if ( lastReceivedMSGs.Count > 5 ) lastReceivedMSGs.RemoveAt( 0 );
  203.     }
  204. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement