Example #1
0
        static void Client(int count)
        {
            // random object used to generate random port
            Random rnd = new Random();

            UdpSocket client = UdpSocket.Create <UdpPlatformManaged, DummySerializer>();

            client.Start(UdpEndPoint.Any);
            client.Connect(new UdpEndPoint(UdpIPv4Address.Localhost, (ushort)(14000 + rnd.Next(count))));

            while (true)
            {
                UdpEvent ev;

                while (client.Poll(out ev))
                {
                    UdpLog.User("Event raised {0}", ev.EventType);

                    switch (ev.EventType)
                    {
                    case UdpEventType.Connected:
                        UdpLog.User("Connected to server at {0}", ev.Connection.RemoteEndPoint);
                        break;
                    }
                }

                // Simulate ~60fps game loop
                Thread.Sleep(16);
            }
        }
Example #2
0
        static void Server(int count)
        {
            UdpSocket[] sockets = new UdpSocket[count];

            for (int i = 0; i < count; ++i)
            {
                sockets[i] = UdpSocket.Create <UdpPlatformManaged, DummySerializer>();
                sockets[i].Start(new UdpEndPoint(UdpIPv4Address.Localhost, (ushort)(14000 + i)));
            }

            UdpSocketMultiplexer multiplexer = UdpSocket.CreateMultiplexer(sockets);

            while (true)
            {
                UdpEvent  ev;
                UdpSocket socket;

                while (multiplexer.Poll(out ev, out socket))
                {
                    UdpLog.User("Event raised {0}", ev.EventType);

                    switch (ev.EventType)
                    {
                    case UdpEventType.Connected:
                        UdpLog.User("Client connected from {0}", ev.Connection.RemoteEndPoint);
                        break;
                    }
                }

                // Simulate ~60fps game loop
                Thread.Sleep(16);
            }
        }
Example #3
0
        public void Start(CClientNetworkCtrl clientNetworkCtrl)
        {
            if (server == null)
            {
                UdpLog.Writer writer = new UdpLog.Writer(DebugImplement);
                //(lvl, s) => Log.info("P2PClientNetWork",  s)
                UdpLog.SetWriter(writer);

                try
                {
                    server = UdpSocket.Create <UdpPlatformManaged, P2PSerializer>();
                }
                catch (Exception e) {
                    Log.info(e, "P2PClientNetWork Start#Exception happened");
                    //MonoBehaviour.print(e);
                }

                //sever and client.
                ConnectServer(clientNetworkCtrl);

                /*
                 * localPort = clientNetworkCtrl.LocalPort;
                 * UdpEndPoint serverPoint = new UdpEndPoint(UdpIPv4Address.Any, (ushort)localPort);
                 * server.Start(serverPoint);
                 * IPAddress ipaddr = IPAddress.Parse (clientNetworkCtrl.ServerIP);
                 * hostUser.ProxyServer = new IPEndPoint( ipaddr, clientNetworkCtrl.ServerPort );
                 *
                 * UdpIPv4Address address = UdpIPv4Address.Parse(clientNetworkCtrl.ServerIP);
                 * UdpEndPoint endp = new UdpEndPoint(address, (ushort)clientNetworkCtrl.ServerPort);
                 * server.Connect( endp );
                 *
                 * Log.info("P2PClientNetWork",  "P2PClientWork Start, UdpPort:" + localPort + " ServerIP:" + clientNetworkCtrl.ServerIP.ToString() + " ProxyServer address:" + endp.ToString());
                 * CtrlOwner = clientNetworkCtrl;*/
            }
        }
Example #4
0
        static void EventLoop(UdpSocket socket)
        {
            UdpConnection c = null;

            while (true)
            {
                UdpEvent ev = default(UdpEvent);

                if (socket.Poll(ref ev))
                {
                    UdpLog.User(ev.EventType.ToString());

                    switch (ev.EventType)
                    {
                    case UdpEventType.ConnectRequest:
                        socket.Accept(ev.EndPoint);
                        break;

                    case UdpEventType.Connected:
                        c = ev.Connection;
                        break;
                    }
                }

                if (c != null)
                {
                    c.Send(10u);
                }

                Thread.Sleep(100);
            }
        }
Example #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Example: Simple");
            Console.WriteLine("Press [S] to start server");
            Console.WriteLine("Press [C] to start client");
            Console.Write("... ");

            UdpLog.SetWriter(Console.WriteLine);

            switch (Console.ReadKey(true).Key)
            {
            case ConsoleKey.S:
                Console.WriteLine("Server");
                Server();
                break;

            case ConsoleKey.C:
                Console.WriteLine("Client");
                Client();
                break;

            default:
                Main(args);
                break;
            }
        }
Example #6
0
        static void Client()
        {
            UdpSocket client = UdpSocket.Create <UdpPlatformManaged, DummySerializer>();

            client.Start(UdpEndPoint.Any);
            client.Connect(new UdpEndPoint(UdpIPv4Address.Localhost, 14000));

            while (true)
            {
                UdpEvent ev = default(UdpEvent);

                while (client.Poll(ref ev))
                {
                    UdpLog.User("Event raised {0}", ev.EventType);

                    switch (ev.EventType)
                    {
                    case UdpEventType.Connected:
                        UdpLog.User("Connected to server at {0}", ev.Connection.RemoteEndPoint);
                        break;

#if DISABLE_AUTO_ACCEPT
                    case UdpEventType.ConnectFailed:
                        UdpLog.User("Connection to {0} failed", ev.EndPoint);
                        break;
#endif
                    }
                }

                // Simulate ~60fps game loop
                Thread.Sleep(16);
            }
        }
Example #7
0
 public void OnPunchFailed(int remotePlayerID)
 {
     UdpLog.Info("[PUNCH FAILED] Local Player {0} with Remote Player {1}", LocalPlayerID(), remotePlayerID);
     if (!this.LocalPlayer.IsMasterClient)
     {
         Instance.ChangeState(ConnectState.DirectFailed);
     }
 }
Example #8
0
        internal void SendObject(object o)
        {
            serializer.SendNext(o);

            while (serializer.HasQueuedObjects)
            {
                UdpSendFailReason reason = CheckCanSend(false);

                if (reason != UdpSendFailReason.None)
                {
                    while (serializer.HasQueuedObjects)
                    {
                        socket.Raise(UdpEvent.PUBLIC_OBJECT_SEND_FAILED, this, serializer.NextObject(), reason);
                    }

                    break;
                }

                UdpStream stream     = socket.GetWriteStream(mtu << 3, UdpSocket.HeaderBitSize);
                var       initialPtr = stream.Ptr; // Erhune: added info
                object    obj        = serializer.NextObject();

                if (serializer.Pack(stream, ref obj))
                {
                    if (stream.Overflowing && (socket.Config.AllowPacketOverflow == false))
                    {
                        UdpLog.Error("Stream to {0} is overflowing (InitialPtr={1} Ptr={2} Len={3}), not sending {4}",
                                     endpoint.ToString(), initialPtr, stream.Ptr, stream.Length, obj); // Erhune: added info
                        socket.Raise(UdpEvent.PUBLIC_OBJECT_SEND_FAILED, this, obj, UdpSendFailReason.StreamOverflow);
                        return;
                    }

                    UdpHeader header = MakeHeader(true);
                    header.Pack(stream, socket, shouldSendClock);

                    UdpHandle handle = MakeHandle(ref header);
                    handle.Object = obj;

                    if (SendStream(stream, handle, alwaysSendMtu))
                    {
                        // track stats
                        stats.PacketSent((uint)stream.Ptr >> 3);
                        socket.Statistics.PacketSent((uint)stream.Ptr >> 3);

                        // push object to user thread
                        socket.Raise(UdpEvent.PUBLIC_OBJECT_SENT, this, obj);
                    }
                    else
                    {
                        socket.Raise(UdpEvent.PUBLIC_OBJECT_SEND_FAILED, this, obj, UdpSendFailReason.SocketError);
                    }
                }
                else
                {
                    socket.Raise(UdpEvent.PUBLIC_OBJECT_SEND_FAILED, this, obj, UdpSendFailReason.SerializerReturnedFalse);
                }
            }
        }
Example #9
0
        public void Loop()
        {
            int      connections = 0;
            UdpEvent ev;

            while (true)
            {
                while (socket.Poll(out ev))
                {
                    switch (ev.EventType)
                    {
                    case UdpEventType.Connected:
                        ++connections;

                        // log in local console
                        UdpLog.User("Client connected from {0}, total clients {1}", ev.Connection.RemoteEndPoint, connections);

                        // send welcome message
                        ev.Connection.Send("Welcome to the chat server!");

                        // send message to all other clients
                        SendToAllClients("Client connected from {0}", ev.Connection.RemoteEndPoint);

                        // add to client list
                        clients.Add(ev.Connection);
                        break;

                    case UdpEventType.Disconnected:
                        --connections;

                        // log in local console
                        UdpLog.User("Client at {0} disconnected, total clients {1}", ev.Connection.RemoteEndPoint, connections);

                        // remove from client list
                        clients.Remove(ev.Connection);

                        // Send message to all others
                        SendToAllClients("Client at {0} disconnected", ev.Connection.RemoteEndPoint);
                        break;

                    // When we receive, just forward to all clients
                    case UdpEventType.ObjectReceived:
                        SendToAllClients(ev.Object as string);
                        break;

                    // If lost, resend to connection it was lost on
                    case UdpEventType.ObjectLost:
                        ev.Connection.Send(ev.Object);
                        break;
                    }
                }

                // Simulate ~60fps game loop
                Thread.Sleep(16);
            }
        }
Example #10
0
        public void OnPunchSuccess(int remotePlayerID, UdpEndPoint remoteEndPoint)
        {
            UdpLog.Info("[PUNCH SUCCESS] Local Player {0} with Remote Player {1}", LocalPlayerID(), remotePlayerID);
            if (!this.LocalPlayer.IsMasterClient)
            {
                BoltNetwork.Connect(remoteEndPoint, Instance.joinToken);
            }

            Instance.joinToken = null;
        }
Example #11
0
        public override bool Pack(ref UdpBitStream buffer, ref object o)
        {
            pair p = (pair)o;

            buffer.WriteUInt(p.seq, 32);
            buffer.WriteUInt(p.val, 32);

            UdpLog.User("sending {0} (seq: {1})", p.val, p.seq);
            return(true);
        }
Example #12
0
  public override int SendTo(byte[] buffer, int bytesToSend, UdpKit.UdpEndPoint endpoint) {
    var bytesSent = NativePInvoke.SendTo(socket, buffer, bytesToSend, endpoint.AsNative);

    if (bytesSent >= 0) {
      return bytesSent;
    }

    UdpLog.Error(Error);
    return -1;
  }
Example #13
0
        public UdpAdpaterConnection(int userdata)
        {
            UdpLog.SetWriter(new UdpLog.Writer(UdpLogWriter));

            UdpPlatform udpPlatform = new DotNetPlatform();

            socket = new UdpSocket(udpPlatform);
            CreateStreamChannel(1, "Default.Udp.StreamChannel", true, 9);
            socket.Start(UdpEndPoint.Any, UdpSocketMode.Client);
            totalTime = 0L;
            beginTime = 0L;
        }
Example #14
0
        public void Ack(pair p)
        {
            if (sendChan.tryAck(p.seq))
            {
                uint seq = 0, val = 0;

                while (sendChan.tryRemoveAcked(ref seq, ref val))
                {
                    UdpLog.User("delivered {0} (seq: {1})", val, seq);
                }
            }
        }
Example #15
0
        public void Loop()
        {
            StreamReader input = new StreamReader(Console.OpenStandardInput());

            Char[]        buffer     = new Char[1024];
            ReadLine      read       = Console.ReadLine;
            IAsyncResult  result     = null;
            UdpConnection connection = null;

            UdpEvent ev;

            while (true)
            {
                while (socket.Poll(out ev))
                {
                    switch (ev.EventType)
                    {
                    case UdpEventType.Connected:
                        UdpLog.User("Connected to server at {0}", ev.Connection.RemoteEndPoint);
                        connection = ev.Connection;
                        break;

                    case UdpEventType.Disconnected:
                        UdpLog.User("Disconnected from server at {0}", ev.Connection.RemoteEndPoint);
                        connection = null;
                        break;

                    case UdpEventType.ObjectReceived:
                        Console.WriteLine(": " + (ev.Object as string));
                        break;
                    }
                }

                if (result == null)
                {
                    result = read.BeginInvoke(null, null);
                }

                if (result.IsCompleted)
                {
                    if (connection != null)
                    {
                        connection.Send(read.EndInvoke(result));
                    }

                    result = read.BeginInvoke(null, null);
                }

                // Simulate ~60fps game loop
                Thread.Sleep(16);
            }
        }
Example #16
0
        static void Main(string[] args)
        {
            if (File.Exists("log.txt"))
            {
                File.Delete("log.txt");
            }

            var fs = File.AppendText("log.txt");

            sockets = new SocketObject[ClientCount + 1];
            Thread th = new Thread(ProcThread);

            UdpLog.SetWriter(s => { fs.WriteLine(s); });

            sockets[0] = new ServerObject();

            for (int i = 1; i < sockets.Length; ++i)
            {
                sockets[i] = new ClientObject();
            }

            start = DateTime.Now;
            th.Start();

            for (int i = 0; i < sockets.Length; ++i)
            {
                sockets[i].Start();
            }

            while (true)
            {
                Console.Clear();

                for (int i = 0; i < sockets[0].connections.Count; ++i)
                {
                    connectionStats(sockets[0].connections[i]);
                }


                Console.WriteLine("-");

                for (int i = 1; i < sockets.Length; ++i)
                {
                    if (sockets[i].connections.Count > 0)
                    {
                        connectionStats(sockets[i].connections[0]);
                    }
                }

                Thread.Sleep(100);
            }
        }
Example #17
0
  public override void Bind(UdpEndPoint ep) {
    try {
      error = null;
      socket.Bind(DotNetPlatform.ConvertEndPoint(ep));

      endpoint = DotNetPlatform.ConvertEndPoint(socket.LocalEndPoint);

      UdpLog.Info("Socket bound to {0}", endpoint);
    }
    catch (SocketException exn) {
      HandleSocketException(exn);
    }
  }
Example #18
0
        void OnStateConnected(UdpConnectionState oldState)
        {
            if (oldState == UdpConnectionState.Connecting)
            {
                UdpLog.Info("connected to {0} ({1})", endpoint.ToString(), mode);

                if (IsServer)
                {
                    SendCommand(UdpCommandType.Accepted);
                }

                socket.Raise(UdpEvent.PUBLIC_CONNECTED, this);
            }
        }
Example #19
0
    void Update()
    {
        UdpEvent ev = default(UdpEvent);

        while (socket.Poll(ref ev))
        {
            switch (ev.EventType)
            {
            case UdpEventType.Connected:
                UdpLog.User("Client connect from {0}", ev.Connection.RemoteEndPoint);
                break;
            }
        }
    }
Example #20
0
  public override int RecvFrom(byte[] buffer, int bufferSize, ref UdpKit.UdpEndPoint endpoint) {
    var sender = default(UdpEndPoint.Native);
    var bytesReceived = NativePInvoke.RecvFrom(socket, buffer, bufferSize, out sender);

    if (bytesReceived > 0) {
      endpoint = sender.AsManaged;
    }

    if (bytesReceived < 0) {
      UdpLog.Error(Error);
      bytesReceived = -1;
    }

    return bytesReceived;
  }
Example #21
0
        internal void ProcessConnectedTimeouts(uint now)
        {
            if ((recvTime + socket.Config.ConnectionTimeout) < now)
            {
                UdpLog.Debug("disconnecting due to timeout from {0}", endpoint);
                ChangeState(UdpConnectionState.Disconnected);
            }

            if (CheckState(UdpConnectionState.Connected))
            {
                if (sendTime + socket.Config.PingTimeout < now || recvSinceLastSend >= socket.Config.RecvWithoutAckLimit)
                {
                    SendCommand(UdpCommandType.Ping);
                }
            }
        }
Example #22
0
 public override void Bind(UdpEndPoint ep)
 {
     try
     {
         this.error = null;
         this.socket.Bind(DotNetPlatform.ConvertEndPoint(ep));
         this.endpoint = DotNetPlatform.ConvertEndPoint(this.socket.LocalEndPoint);
         UdpLog.Info("Socket bound to {0}", new object[]
         {
             this.endpoint
         });
     }
     catch (SocketException exn)
     {
         this.HandleSocketException(exn);
     }
 }
Example #23
0
        bool SendConnectRequest()
        {
            if (connectAttempts < socket.Config.ConnectRequestAttempts)
            {
                if (connectAttempts != 0)
                {
                    UdpLog.Info("retrying connection to {0}", endpoint.ToString());
                }

                SendCommand(UdpCommandType.Connect);

                connectTimeout   = socket.GetCurrentTime() + socket.Config.ConnectRequestTimeout;
                connectAttempts += 1u;
                return(true);
            }

            return(false);
        }
Example #24
0
        static void Main(string[] args)
        {
            Console.BufferHeight = 5000;

            UdpLog.SetWriter(Console.WriteLine);

            serverThread = new Thread(Server);
            serverThread.IsBackground = true;
            serverThread.Name         = "server";
            serverThread.Start();

            clientThread = new Thread(Client);
            clientThread.IsBackground = true;
            clientThread.Name         = "client";
            clientThread.Start();

            Console.ReadLine();
        }
Example #25
0
        void ConnectionError(UdpConnectionError error, string message)
        {
            UdpLog.Debug("error '{0} - {2}' on connection to {1}", error.ToString(), endpoint.ToString(), message);

            switch (error)
            {
            case UdpConnectionError.SequenceOutOfBounds:
                ChangeState(UdpConnectionState.Disconnected);
                break;

            case UdpConnectionError.IncorrectCommand:
                ChangeState(UdpConnectionState.Disconnected);
                break;

            case UdpConnectionError.SendWindowFull:
                ChangeState(UdpConnectionState.Disconnected);
                break;
            }
        }
Example #26
0
        public void DequeueReceived()
        {
            uint seq = 0, val = 0;

            while (recvChan.tryRemove(ref seq, ref val))
            {
                if (val != recvNext)
                {
                    throw new Exception();
                }

                UdpLog.User("received {0} (seq: {1})", val, seq);
                recvNext = val + 1u;

                if (recvNext == toNumber)
                {
                    done = true;
                }
            }
        }
Example #27
0
    private List <UdpPlatformInterface> FindInterfaces()
    {
        List <UdpPlatformInterface> list = new List <UdpPlatformInterface>();

        try
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
                for (int i = 0; i < allNetworkInterfaces.Length; i++)
                {
                    NetworkInterface networkInterface = allNetworkInterfaces[i];
                    try
                    {
                        if (networkInterface.OperationalStatus == OperationalStatus.Up || networkInterface.OperationalStatus == OperationalStatus.Unknown)
                        {
                            if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                            {
                                DotNetInterface dotNetInterface = this.ParseInterface(networkInterface);
                                if (dotNetInterface != null)
                                {
                                    list.Add(dotNetInterface);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        UdpLog.Error(ex.Message, new object[0]);
                    }
                }
            }
        }
        catch (Exception ex2)
        {
            UdpLog.Error(ex2.Message, new object[0]);
        }
        return(list);
    }
Example #28
0
  bool CheckResult(int result) {
    if (result == NativePInvoke.UDPKIT_SOCKET_OK) {
      return true;
    }

    if (result == NativePInvoke.UDPKIT_SOCKET_ERROR) {
      UdpLog.Error(Error);
      UdpLog.Error(System.Environment.StackTrace);
      return false;
    }

    if (result == NativePInvoke.UDPKIT_SOCKET_NOTVALID) {
      UdpLog.Error("Invalid socket pointer: {0}", socket);
      return false;
    }

    if (result == NativePInvoke.UDPKIT_SOCKET_NODATA) {
      return false;
    }

    throw new Exception(string.Format("Unknown return code: {0}", result));
  }
Example #29
0
        static void Server()
        {
#if DISABLE_AUTO_ACCEPT
            UdpConfig config = new UdpConfig();
            config.AutoAcceptIncommingConnections = false;
#else
            UdpConfig config = new UdpConfig();
#endif
            UdpSocket server = UdpSocket.Create <UdpPlatformManaged, DummySerializer>(config);
            server.Start(new UdpEndPoint(UdpIPv4Address.Localhost, 14000));

            while (true)
            {
                UdpEvent ev = default(UdpEvent);

                while (server.Poll(ref ev))
                {
                    UdpLog.User("Event raised {0}", ev.EventType);

                    switch (ev.EventType)
                    {
                    case UdpEventType.Connected:
                        UdpLog.User("Client connected from {0}, total clients connected: {1}", ev.Connection.RemoteEndPoint, server.ConnectionCount);
                        break;

#if ENABLE_MANUAL_ACCEPT
                    case UdpEventType.ConnectRequest:
                        UdpLog.User("Connection requested from {0}", ev.EndPoint);
                        server.Accept(ev.EndPoint);
                        break;
#endif
                    }
                }

                // Simulate ~60fps game loop
                Thread.Sleep(16);
            }
        }
Example #30
0
  List<UdpPlatformInterface> FindInterfaces() {
#if UNITY_WEBPLAYER
    return new List<UdpPlatformInterface>();
#else
    List<UdpPlatformInterface> result = new List<UdpPlatformInterface>();

    try {
      if (NetworkInterface.GetIsNetworkAvailable()) {
        foreach (var n in NetworkInterface.GetAllNetworkInterfaces()) {
          try {
            if (n.OperationalStatus != OperationalStatus.Up && n.OperationalStatus != OperationalStatus.Unknown) {
              continue;
            }

            if (n.NetworkInterfaceType == NetworkInterfaceType.Loopback) {
              continue;
            }

            var iface = ParseInterface(n);
            if (iface != null) {
              result.Add(iface);
            }
          }
          catch (System.Exception exn) {
            UdpLog.Error(exn.Message);
          }
        }
      }
    }
    catch (System.Exception exn) {
      UdpLog.Error(exn.Message);
    }

    return result;
#endif
  }