예제 #1
0
파일: Host.cs 프로젝트: broccoli47/chat
    public void ConnectToServer(string ServerIP)
    {
        if (state == InternetState.None)
        {
            state = InternetState.Client;

            HostTopology topology = new HostTopology(config, 1);
            HostID = NetworkTransport.AddHost(topology);

            byte error;
            ConnectionID = NetworkTransport.Connect(HostID, ServerIP, ServerPort, 0, out error);

            if (ConnectionID > 0)
            {
                Log.Server("Connecting to " + ServerIP);
            }
            else
            {
                Log.Error("Maximum amount of connections exceeded");
            }
        }
        else
        {
            Log.Error("You cannot connect in your current network state.");
        }
    }
예제 #2
0
        /// <summary>
        /// Moves the internet connection state to the specified new state.
        /// </summary>
        /// <param name="newState">State of the new.</param>
        public void MoveInternetConnectionStateTo(InternetState newState)
        {
            InternetState oldState = internetConnectionState;

            internetConnectionState = newState;
            if (InternetConnectionStateMoved != null)
            {
                try {
                    InternetConnectionStateMoved(this, new InternetConnectionStateChangeEventArgs(oldState, newState));
                } catch {}
            }
        }
예제 #3
0
파일: Host.cs 프로젝트: broccoli47/chat
    public void InitializeServer()
    {
        if (state == InternetState.None)
        {
            state = InternetState.Server;
            HostTopology topology = new HostTopology(config, MaxConnections);
            HostID = NetworkTransport.AddHost(topology, ServerPort);

            Log.Server("Starting Server");
            Log.Line(" IP address: " + MyIP);
            Log.Line(" Port: " + ServerPort.ToString());
            Log.Line(" Max Connections: " + MaxConnections.ToString());
        }
    }
예제 #4
0
 static void socketAsync_Completed <T>(object sender, SocketAsyncEventArgs e)
 {
     if (e.LastOperation == SocketAsyncOperation.Connect)
     {
         Socket            skt   = sender as Socket;
         InternetState <T> state = e.UserToken as InternetState <T>;
         if (state != null)
         {
             LoggingMethod.WriteToLog(string.Format("DateTime {0} socketAsync_Completed.", DateTime.Now.ToString()), LoggingMethod.LevelInfo);
             state.Callback(true);
         }
         mreSocketAsync.Set();
     }
 }
예제 #5
0
파일: Host.cs 프로젝트: broccoli47/chat
    public void InitInternet()
    {
        if (state == InternetState.Offline)
        {
            Log.Line("Initializing Network Transport");
            MyIP = Network.player.ipAddress;
            Log.Line("Allocating network buffer (" + BufferSize.ToString() + " bytes)");
            Buffer = new byte[BufferSize];

            GlobalConfig gconfig = new GlobalConfig();
            gconfig.MaxPacketSize = 512;

            NetworkTransport.Init(gconfig);

            Log.Line("Creating Reliable and Unreliable channels");
            config     = new ConnectionConfig();
            Unreliable = config.AddChannel(QosType.Unreliable);
            Reliable   = config.AddChannel(QosType.Reliable);

            state = InternetState.None;
        }
    }
예제 #6
0
        private static void CheckClientNetworkAvailability <T>(Action <bool> callback, Action <PubnubClientError> errorCallback, string[] channels, string[] channelGroups)
        {
            InternetState <T> state = new InternetState <T>();

            state.Callback      = callback;
            state.ErrorCallback = errorCallback;
            state.Channels      = channels;
            state.ChannelGroups = channelGroups;
            #if (UNITY_ANDROID || UNITY_IOS || NETFX_CORE)
            CheckSocketConnect <T>(state);
                        #elif (__MonoCS__)
            CheckSocketConnect <T>(state);
                        #else
            ThreadPool.QueueUserWorkItem(CheckSocketConnect <T>, state);
                        #endif

                        #if (SILVERLIGHT || WINDOWS_PHONE)
            mres.WaitOne();
                        #elif (!UNITY_ANDROID && !UNITY_IOS)
            mres.Wait();
                        #endif
        }
예제 #7
0
        /// <summary>
        /// Отправить
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Send_Click(object sender, RoutedEventArgs e)
        {
            if (InternetState.CheckForInternetConnection())
            {
                email.Subject = subjectText.Text;

                TextRange textRange = new TextRange(bodyText.Document.ContentStart, bodyText.Document.ContentEnd);

                email.Body = textRange.Text;

                Task.Run(() => { email.Send(); });

                ContexTrayMenu.ShowMessage("Уведомление!", "Сообщение было успешно отправлено!", System.Windows.Forms.ToolTipIcon.Info);

                attachmentsPanel.Children.Clear();
                EmailSender.attachmentsView.Clear();

                (Application.Current.MainWindow as MenuWindow).mainFrame.Content = new UsersPage();
            }
            else
            {
                ContexTrayMenu.ShowMessage("Ошибка!", "Отсутствует подключение к интернету!", System.Windows.Forms.ToolTipIcon.Error);
            }
        }
예제 #8
0
 /// <summary>Initializer.</summary>
 /// <param name="currentState">INetState</param>
 /// <param name="newState">INetState</param>
 public InternetConnectionStateChangeEventArgs(InternetState currentState, InternetState newState)
 {
     this._currentState = currentState;
     this._newState     = newState;
 }
예제 #9
0
파일: Host.cs 프로젝트: broccoli47/chat
 public void Shutdown()
 {
     NetworkTransport.Shutdown();
     Log.Line("All network activity has been terminated.");
     state = InternetState.Offline;
 }
예제 #10
0
        private static void CheckSocketConnect <T>(object internetState)
        {
            InternetState <T>          state         = internetState as InternetState <T>;
            Action <bool>              callback      = state.Callback;
            Action <PubnubClientError> errorCallback = state.ErrorCallback;

            string[] channels      = state.Channels;
            string[] channelGroups = state.ChannelGroups;
            try
            {
                                #if (SILVERLIGHT || WINDOWS_PHONE)
                using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    SocketAsyncEventArgs sae = new SocketAsyncEventArgs();
                    sae.UserToken      = state;
                    sae.RemoteEndPoint = new DnsEndPoint("pubsub.pubnub.com", 80);
                    sae.Completed     += new EventHandler <SocketAsyncEventArgs>(socketAsync_Completed <T>);
                    bool test = socket.ConnectAsync(sae);

                    mreSocketAsync.WaitOne(1000);
                    sae.Completed -= new EventHandler <SocketAsyncEventArgs>(socketAsync_Completed <T>);
                    socket.Close();
                }
                #elif NETFX_CORE
                CheckSocketConnectAsync();
                #elif (UNITY_IOS || UNITY_ANDROID)
                request = (HttpWebRequest)WebRequest.Create("http://pubsub.pubnub.com");
                if (request != null)
                {
                    request.Timeout     = HeartbeatInterval * 1000;
                    request.ContentType = "application/json";
                    response            = request.GetResponse();
                    if (response != null)
                    {
                        if (((HttpWebResponse)response).ContentLength <= 0)
                        {
                            _status = false;
                            throw new Exception("Failed to connect");
                        }
                        else
                        {
                            using (Stream dataStream = response.GetResponseStream()){
                                using (StreamReader reader = new StreamReader(dataStream)){
                                    string responseFromServer = reader.ReadToEnd();
                                    LoggingMethod.WriteToLog(string.Format("DateTime {0}, Response:{1}", DateTime.Now.ToString(), responseFromServer), LoggingMethod.LevelInfo);
                                    _status = true;
                                    callback(true);
                                    reader.Close();
                                }
                                dataStream.Close();
                            }
                        }
                    }
                }
                                #elif (__MonoCS__)
                udp = new UdpClient("pubsub.pubnub.com", 80);
                IPAddress localAddress = ((IPEndPoint)udp.Client.LocalEndPoint).Address;
                if (udp != null && udp.Client != null)
                {
                    EndPoint remotepoint   = udp.Client.RemoteEndPoint;
                    string   remoteAddress = (remotepoint != null) ? remotepoint.ToString() : "";
                    LoggingMethod.WriteToLog(string.Format("DateTime {0} checkInternetStatus LocalIP: {1}, RemoteEndPoint:{2}", DateTime.Now.ToString(), localAddress.ToString(), remoteAddress), LoggingMethod.LevelVerbose);
                    _status = true;
                    callback(true);
                }
                                #else
                using (UdpClient udp = new UdpClient("pubsub.pubnub.com", 80))
                {
                    IPAddress localAddress  = ((IPEndPoint)udp.Client.LocalEndPoint).Address;
                    EndPoint  remotepoint   = udp.Client.RemoteEndPoint;
                    string    remoteAddress = (remotepoint != null) ? remotepoint.ToString() : "";
                    udp.Close();

                    LoggingMethod.WriteToLog(string.Format("DateTime {0} checkInternetStatus LocalIP: {1}, RemoteEndPoint:{2}", DateTime.Now.ToString(), localAddress.ToString(), remoteAddress), LoggingMethod.LevelVerbose);
                    callback(true);
                }
                                #endif
            }
                        #if (UNITY_IOS || UNITY_ANDROID)
            catch (WebException webEx) {
                if (webEx.Message.Contains("404"))
                {
                    _status = true;
                    callback(true);
                }
                else
                {
                    _status = false;
                    ParseCheckSocketConnectException <T>(webEx, channels, errorCallback, callback);
                }
            }
                        #endif
            catch (Exception ex)
            {
                                #if (__MonoCS__)
                _status = false;
                                #endif
                ParseCheckSocketConnectException <T>(ex, channels, channelGroups, errorCallback, callback);
            }
            finally
            {
                                #if (UNITY_IOS || UNITY_ANDROID)
                if (response != null)
                {
                    response.Close();

                    response = null;
                }

                if (request != null)
                {
                    request = null;
                }
                                #elif (__MonoCS__)
                if (udp != null)
                {
                    udp.Close();
                }
                                #endif
                                #if (UNITY_IOS)
                GC.Collect();
                                #endif
            }
                        #if (!UNITY_ANDROID && !UNITY_IOS)
            mres.Set();
                        #endif
        }