예제 #1
0
 //-------------------------------------------------------------------------
 /// <summary>
 /// Asserts that the object can be serialized and deserialized to an equal form.
 /// </summary>
 /// <param name="base">  the object to be tested </param>
 public static void assertSerialization(object @base)
 {
     assertNotNull(@base);
     try
     {
         using (MemoryStream baos = new MemoryStream())
         {
             using (ObjectOutputStream oos = new ObjectOutputStream(baos))
             {
                 oos.writeObject(@base);
                 oos.close();
                 using (MemoryStream bais = new MemoryStream(baos.toByteArray()))
                 {
                     using (ObjectInputStream ois = new ObjectInputStream(bais))
                     {
                         assertEquals(ois.readObject(), @base);
                     }
                 }
             }
         }
     }
     catch (Exception ex) when(ex is IOException || ex is ClassNotFoundException)
     {
         throw new Exception(ex);
     }
 }
예제 #2
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static Object deepCopy(Object paramObject) throws Exception
        public static object deepCopy(object paramObject)
        {
            objectOutputStream = null;
            objectInputStream  = null;
            try
            {
                MemoryStream byteArrayOutputStream = new MemoryStream();
                objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                objectOutputStream.writeObject(paramObject);
                objectOutputStream.flush();
                MemoryStream byteArrayInputStream = new MemoryStream(byteArrayOutputStream.toByteArray());
                objectInputStream = new ObjectInputStream(byteArrayInputStream);
                return(objectInputStream.readObject());
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception in ObjectCloner = " + exception);
                throw exception;
            }
            finally
            {
                objectOutputStream.close();
                objectInputStream.close();
            }
        }
예제 #3
0
        /// <summary>
        /// Saves this training set to file specified in its filePath field
        /// </summary>
        public virtual void save()
        {
            ObjectOutputStream @out = null;

            try
            {
                File file = new File(this.filePath);
                @out = new ObjectOutputStream(new FileOutputStream(file));
                @out.writeObject(this);
                @out.flush();
            }
            catch (IOException ioe)
            {
                throw new NeurophException(ioe);
            }
            finally
            {
                if (@out != null)
                {
                    try
                    {
                        @out.close();
                    }
                    catch (IOException)
                    {
                    }
                }
            }
        }
예제 #4
0
    // Connect to server address at port 1337 (main server) and get a new port on which to login or sign up.
    public void connectToMainServer(bool newAcct)
    {
        Socket cnxn = null;

        try {
            // 1st step: Connect to main server and send handshake.
            cnxn = new Socket(ip, 1337);

            ObjectOutputStream output = new ObjectOutputStream(cnxn.getOutputStream());
            output.writeInt(handshake);
            output.flush();

            // Must now send username.
            string username = newAcct ? usernameReg.text : usernameLogin.text;
            output.writeObject(username);
            output.flush();

            // Receive whatever port the server sends (random or determined).
            cnxn.setSoTimeout(10000);             // 10-sec timeout for input reads
            ObjectInputStream input = new ObjectInputStream(cnxn.getInputStream());
            int nextPort            = input.readInt();

            // Close streams and connection.
            input.close();
            output.close();
            cnxn.close();

            // We got a port now! At this point, either log in or sign up.
            if (newAcct)
            {
                signup(nextPort);
            }
            else
            {
                loginAndPlay(nextPort);
            }
        } catch (java.lang.Exception e) {
            // Display some kind of error window if there was a connection error (basically a Java exception).
            // If the socket is null, the connection attempt failed; otherwise, the connection timed out, or something else happened.
            StartMenuScript sms = (StartMenuScript)(startMenu.GetComponent(typeof(StartMenuScript)));
            if (cnxn == null)
            {
                sms.RaiseErrorWindow("Failed to connect. Check your connection settings. The main server may be down.");
            }
            else if (e.GetType() == typeof(SocketTimeoutException))
            {
                sms.RaiseErrorWindow("Connection timed out. Check your connection. The main server may have gone down.");
            }
            else
            {
                sms.RaiseErrorWindow("An unknown exception occurred when trying to connect to the main server.");
            }
        } catch (System.Exception e) {
            // This handles C# exceptions. These shouldn't happen, which is why the errors are printed to the console (for us to test for ourselves).
            print("Encountered a C# exception:\n");
            print(e.Message);
        }
    }
예제 #5
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private Payload payloadFor(Object value) throws java.io.IOException
        private Payload PayloadFor(object value)
        {
            MemoryStream       bout = new MemoryStream();
            ObjectOutputStream oout = new ObjectOutputStream(bout);

            oout.writeObject(value);
            oout.close();
            sbyte[] bytes = bout.toByteArray();
            return(new Payload(bytes, bytes.Length));
        }
예제 #6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void resourcesToSer(Desktop.common.nomitech.common.base.BaseTableList paramBaseTableList, java.io.File paramFile) throws Exception
        public virtual void resourcesToSer(BaseTableList paramBaseTableList, File paramFile)
        {
            FileStream           fileOutputStream     = new FileStream(paramFile, FileMode.Create, FileAccess.Write);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            ObjectOutputStream   objectOutputStream   = new ObjectOutputStream(bufferedOutputStream);

            try
            {
                objectOutputStream.writeObject(paramBaseTableList);
            }
            catch (Exception exception)
            {
                objectOutputStream.close();
                Console.WriteLine(exception.ToString());
                Console.Write(exception.StackTrace);
                throw exception;
            }
            objectOutputStream.close();
        }
예제 #7
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void worksheetTemplateToSer(Desktop.common.nomitech.common.db.project.WorksheetRevisionTable paramWorksheetRevisionTable, java.io.File paramFile) throws Exception
        public virtual void worksheetTemplateToSer(WorksheetRevisionTable paramWorksheetRevisionTable, File paramFile)
        {
            FileStream           fileOutputStream     = new FileStream(paramFile, FileMode.Create, FileAccess.Write);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            ObjectOutputStream   objectOutputStream   = new ObjectOutputStream(bufferedOutputStream);

            try
            {
                objectOutputStream.writeObject(paramWorksheetRevisionTable);
            }
            catch (Exception exception)
            {
                objectOutputStream.close();
                Console.WriteLine(exception.ToString());
                Console.Write(exception.StackTrace);
                throw exception;
            }
            objectOutputStream.close();
        }
예제 #8
0
        public virtual void saveModel(string filename)
        {
            FileOutputStream     fileOutputStream     = new FileOutputStream(filename);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            ObjectOutputStream   objectOutputStream   = new ObjectOutputStream(bufferedOutputStream);

            this.writeFst(objectOutputStream);
            objectOutputStream.flush();
            objectOutputStream.close();
            bufferedOutputStream.close();
            fileOutputStream.close();
        }
예제 #9
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private byte[] writeObject(Object object) throws java.io.IOException
        private sbyte[] writeObject(object @object)
        {
            MemoryStream buffer = new MemoryStream();

            ObjectOutputStream outputStream = new ObjectOutputStream(buffer);

            outputStream.writeObject(@object);
            outputStream.flush();
            outputStream.close();

            return(buffer.toByteArray());
        }
예제 #10
0
        /**
         * Gets the size of the provided area code map storage. The map storage passed-in will be filled
         * as a result.
         */
        private static int getSizeOfAreaCodeMapStorage(AreaCodeMapStorageStrategy mapStorage,
                                                       SortedMap <Integer, String> areaCodeMap)
        {
            mapStorage.readFromSortedMap(areaCodeMap);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream    objectOutputStream    = new ObjectOutputStream(byteArrayOutputStream);

            mapStorage.writeExternal(objectOutputStream);
            objectOutputStream.flush();
            int sizeOfStorage = byteArrayOutputStream.size();

            objectOutputStream.close();
            return(sizeOfStorage);
        }
예제 #11
0
 public static void save(string fname, object obj)
 {
     try
     {
         FileOutputStream fs = new FileOutputStream(fname);
         ObjectOutputStream @out = new ObjectOutputStream(fs);
         @out.writeObject(obj);
         @out.close();
     }
     catch(Exception ex)
     {
         ex.printStackTrace();
     }
 }
예제 #12
0
 protected internal virtual void WriteFailureResponse(Exception exception, ChunkingChannelBuffer buffer)
 {
     try
     {
         MemoryStream       bytes = new MemoryStream();
         ObjectOutputStream @out  = new ObjectOutputStream(bytes);
         @out.writeObject(exception);
         @out.close();
         buffer.WriteBytes(bytes.toByteArray());
         buffer.Done();
     }
     catch (IOException)
     {
         _msgLog.warn("Couldn't send cause of error to client", exception);
     }
 }
예제 #13
0
파일: FaultSkin.cs 프로젝트: Veggie13/ipf
        public static void writeToFileSlow(String fileName, FaultSkin skin)
        {
            throw new NotImplementedException();
#if false
            try
            {
                FileOutputStream   fos = new FileOutputStream(fileName);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(skin);
                oos.close();
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }
#endif
        }
예제 #14
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: protected void saveFeatureMap(java.io.OutputStream os, org.maltparser.ml.lib.FeatureMap map) throws org.maltparser.core.exception.MaltChainedException
        protected internal virtual void saveFeatureMap(Stream os, FeatureMap map)
        {
            try
            {
                ObjectOutputStream output = new ObjectOutputStream(os);
                try
                {
                    output.writeObject(map);
                }
                finally
                {
                    output.close();
                }
            }
            catch (IOException e)
            {
                throw new LibException("Save feature map error", e);
            }
        }
예제 #15
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static byte[] serialize(MemberIsUnavailable message) throws java.io.IOException
        private static sbyte[] Serialize(MemberIsUnavailable message)
        {
            ObjectOutputStream outputStream = null;

            try
            {
                MemoryStream byteArrayOutputStream = new MemoryStream();
                outputStream = (new ObjectStreamFactory()).create(byteArrayOutputStream);
                outputStream.writeObject(message);
                return(byteArrayOutputStream.toByteArray());
            }
            finally
            {
                if (outputStream != null)
                {
                    outputStream.close();
                }
            }
        }
예제 #16
0
        private static void saveModel(Classifier c, String name, java.io.File fileName)
        {
            ObjectOutputStream oos = null;

            try
            {
                oos = new ObjectOutputStream(
                    new FileOutputStream("..\\..\\..\\..\\libs\\models\\" + "models" + name + ".model"));
            }
            catch (java.io.FileNotFoundException e1)
            {
                e1.printStackTrace();
            }
            catch (java.io.IOException e1)
            {
                e1.printStackTrace();
            }
            oos.writeObject(c);
            oos.flush();
            oos.close();
        }
예제 #17
0
        /// <summary>
        /// Saves neural network into the specified file.
        /// </summary>
        /// <param name="filePath"> file path to save network into </param>
        public virtual void save(string filePath)
        {
            ObjectOutputStream @out = null;

            try {
                File file = new File(filePath);
                @out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
                @out.writeObject(this);
                @out.flush();
            } catch (IOException ioe) {
                throw new NeurophException("Could not write neural network to file!", ioe);
            } finally {
                if (@out != null)
                {
                    try {
                        @out.close();
                    } catch (IOException) {
                    }
                }
            }
        }
예제 #18
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: protected void trainExternal(String pathExternalTrain, java.util.LinkedHashMap<String, String> libOptions) throws org.maltparser.core.exception.MaltChainedException
        protected internal override void trainExternal(string pathExternalTrain, LinkedHashMap <string, string> libOptions)
        {
            try
            {
                binariesInstances2SVMFileFormat(getInstanceInputStreamReader(".ins"), getInstanceOutputStreamWriter(".ins.tmp"));
                Configuration config = Configuration;

                if (config.LoggerInfoEnabled)
                {
                    config.logInfoMessage("Creating learner model (external) " + getFile(".mod").Name);
                }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final libsvm.svm_problem prob = readProblem(getInstanceInputStreamReader(".ins"), libOptions);
                svm_problem prob = readProblem(getInstanceInputStreamReader(".ins"), libOptions);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String[] params = getLibParamStringArray(libOptions);
                string[] @params       = getLibParamStringArray(libOptions);
                string[] arrayCommands = new string[@params.Length + 3];
                int      i             = 0;
                arrayCommands[i++] = pathExternalTrain;
                for (; i <= @params.Length; i++)
                {
                    arrayCommands[i] = @params[i - 1];
                }
                arrayCommands[i++] = getFile(".ins.tmp").AbsolutePath;
                arrayCommands[i++] = getFile(".mod").AbsolutePath;

                if (verbosity == Verbostity.ALL)
                {
                    config.logInfoMessage('\n');
                }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final Process child = Runtime.getRuntime().exec(arrayCommands);
                Process child = Runtime.Runtime.exec(arrayCommands);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.InputStream in = child.getInputStream();
                Stream @in = child.InputStream;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.InputStream err = child.getErrorStream();
                Stream err = child.ErrorStream;
                int    c;
                while ((c = @in.Read()) != -1)
                {
                    if (verbosity == Verbostity.ALL)
                    {
                        config.logInfoMessage((char)c);
                    }
                }
                while ((c = err.Read()) != -1)
                {
                    if (verbosity == Verbostity.ALL || verbosity == Verbostity.ERROR)
                    {
                        config.logInfoMessage((char)c);
                    }
                }
                if (child.waitFor() != 0)
                {
                    config.logErrorMessage(" FAILED (" + child.exitValue() + ")");
                }
                @in.Close();
                err.Close();
                svm_model          model  = svm.svm_load_model(getFile(".mod").AbsolutePath);
                MaltLibsvmModel    xmodel = new MaltLibsvmModel(model, prob);
                ObjectOutputStream output = new ObjectOutputStream(new BufferedOutputStream(new FileStream(getFile(".moo").AbsolutePath, FileMode.Create, FileAccess.Write)));
                try
                {
                    output.writeObject(xmodel);
                }
                finally
                {
                    output.close();
                }
                bool saveInstanceFiles = ((bool?)Configuration.getOptionValue("lib", "save_instance_files")).Value;
                if (!saveInstanceFiles)
                {
                    getFile(".ins").delete();
                    getFile(".mod").delete();
                    getFile(".ins.tmp").delete();
                }
                if (config.LoggerInfoEnabled)
                {
                    config.logInfoMessage('\n');
                }
            }
            catch (InterruptedException e)
            {
                throw new LibException("Learner is interrupted. ", e);
            }
            catch (ArgumentException e)
            {
                throw new LibException("The learner was not able to redirect Standard Error stream. ", e);
            }
            catch (SecurityException e)
            {
                throw new LibException("The learner cannot remove the instance file. ", e);
            }
            catch (IOException e)
            {
                throw new LibException("The learner cannot save the model file '" + getFile(".mod").AbsolutePath + "'. ", e);
            }
            catch (OutOfMemoryException e)
            {
                throw new LibException("Out of memory. Please increase the Java heap size (-Xmx<size>). ", e);
            }
        }
예제 #19
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: protected void trainInternal(java.util.LinkedHashMap<String, String> libOptions) throws org.maltparser.core.exception.MaltChainedException
        protected internal override void trainInternal(LinkedHashMap <string, string> libOptions)
        {
            try
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final libsvm.svm_problem prob = readProblem(getInstanceInputStreamReader(".ins"), libOptions);
                svm_problem prob = readProblem(getInstanceInputStreamReader(".ins"), libOptions);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final libsvm.svm_parameter param = getLibSvmParameters(libOptions);
                svm_parameter param = getLibSvmParameters(libOptions);
                if (svm.svm_check_parameter(prob, param) != null)
                {
                    throw new LibException(svm.svm_check_parameter(prob, param));
                }
                Configuration config = Configuration;

                if (config.LoggerInfoEnabled)
                {
                    config.logInfoMessage("Creating LIBSVM model " + getFile(".moo").Name + "\n");
                }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.PrintStream out = System.out;
                PrintStream @out = System.out;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.PrintStream err = System.err;
                PrintStream err = System.err;
                System.Out = NoPrintStream.NO_PRINTSTREAM;
                System.Err = NoPrintStream.NO_PRINTSTREAM;
                svm_model model = svm.svm_train(prob, param);
                System.Out = err;
                System.Out = @out;
                ObjectOutputStream output = new ObjectOutputStream(new BufferedOutputStream(new FileStream(getFile(".moo").AbsolutePath, FileMode.Create, FileAccess.Write)));
                try
                {
                    output.writeObject(new MaltLibsvmModel(model, prob));
                }
                finally
                {
                    output.close();
                }
                bool saveInstanceFiles = ((bool?)Configuration.getOptionValue("lib", "save_instance_files")).Value;
                if (!saveInstanceFiles)
                {
                    getFile(".ins").delete();
                }
            }
            catch (OutOfMemoryException e)
            {
                throw new LibException("Out of memory. Please increase the Java heap size (-Xmx<size>). ", e);
            }
            catch (ArgumentException e)
            {
                throw new LibException("The LIBSVM learner was not able to redirect Standard Error stream. ", e);
            }
            catch (SecurityException e)
            {
                throw new LibException("The LIBSVM learner cannot remove the instance file. ", e);
            }
            catch (IOException e)
            {
                throw new LibException("The LIBSVM learner cannot save the model file '" + getFile(".mod").AbsolutePath + "'. ", e);
            }
        }
예제 #20
0
 public override void close()
 {
     output.flush();
     output.close();
 }
예제 #21
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: protected void trainInternal(java.util.LinkedHashMap<String, String> libOptions) throws org.maltparser.core.exception.MaltChainedException
        protected internal override void trainInternal(LinkedHashMap <string, string> libOptions)
        {
            Configuration config = Configuration;

            if (config.LoggerInfoEnabled)
            {
                config.logInfoMessage("Creating Liblinear model " + getFile(".moo").Name + "\n");
            }
            double[]  wmodel     = null;
            int[]     labels     = null;
            int       nr_class   = 0;
            int       nr_feature = 0;
            Parameter parameter  = getLiblinearParameters(libOptions);

            try
            {
                Problem problem = readProblem(getInstanceInputStreamReader(".ins"));
                bool    res     = checkProblem(problem);
                if (res == false)
                {
                    throw new LibException("Abort (The number of training instances * the number of classes) > " + int.MaxValue + " and this is not supported by LibLinear. ");
                }
                if (config.LoggerInfoEnabled)
                {
                    config.logInfoMessage("- Train a parser model using LibLinear.\n");
                }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.PrintStream out = System.out;
                PrintStream @out = System.out;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.PrintStream err = System.err;
                PrintStream err = System.err;
                System.Out = NoPrintStream.NO_PRINTSTREAM;
                System.Err = NoPrintStream.NO_PRINTSTREAM;
                Model model = Linear.train(problem, parameter);
                System.Out = err;
                System.Out = @out;
                problem    = null;
                wmodel     = model.FeatureWeights;
                labels     = model.Labels;
                nr_class   = model.NrClass;
                nr_feature = model.NrFeature;
                bool saveInstanceFiles = ((bool?)Configuration.getOptionValue("lib", "save_instance_files")).Value;
                if (!saveInstanceFiles)
                {
                    getFile(".ins").delete();
                }
            }
            catch (OutOfMemoryException e)
            {
                throw new LibException("Out of memory. Please increase the Java heap size (-Xmx<size>). ", e);
            }
            catch (ArgumentException e)
            {
                throw new LibException("The Liblinear learner was not able to redirect Standard Error stream. ", e);
            }
            catch (SecurityException e)
            {
                throw new LibException("The Liblinear learner cannot remove the instance file. ", e);
            }
            catch (NegativeArraySizeException e)
            {
                throw new LibException("(The number of training instances * the number of classes) > " + int.MaxValue + " and this is not supported by LibLinear.", e);
            }

            if (config.LoggerInfoEnabled)
            {
                config.logInfoMessage("- Optimize the memory usage\n");
            }
            MaltLiblinearModel xmodel = null;

            try
            {
                //			System.out.println("Nr Features:" +  nr_feature);
                //			System.out.println("nr_class:" + nr_class);
                //			System.out.println("wmodel.length:" + wmodel.length);
                double[][] wmatrix = convert2(wmodel, nr_class, nr_feature);
                xmodel = new MaltLiblinearModel(labels, nr_class, wmatrix.Length, wmatrix, parameter.SolverType);
                if (config.LoggerInfoEnabled)
                {
                    config.logInfoMessage("- Save the Liblinear model " + getFile(".moo").Name + "\n");
                }
            }
            catch (OutOfMemoryException e)
            {
                throw new LibException("Out of memory. Please increase the Java heap size (-Xmx<size>). ", e);
            }
            try
            {
                if (xmodel != null)
                {
                    ObjectOutputStream output = new ObjectOutputStream(new BufferedOutputStream(new FileStream(getFile(".moo").AbsolutePath, FileMode.Create, FileAccess.Write)));
                    try
                    {
                        output.writeObject(xmodel);
                    }
                    finally
                    {
                        output.close();
                    }
                }
            }
            catch (OutOfMemoryException e)
            {
                throw new LibException("Out of memory. Please increase the Java heap size (-Xmx<size>). ", e);
            }
            catch (ArgumentException e)
            {
                throw new LibException("The Liblinear learner was not able to redirect Standard Error stream. ", e);
            }
            catch (SecurityException e)
            {
                throw new LibException("The Liblinear learner cannot remove the instance file. ", e);
            }
            catch (IOException e)
            {
                throw new LibException("The Liblinear learner cannot save the model file '" + getFile(".mod").AbsolutePath + "'. ", e);
            }
        }
예제 #22
0
    // Sign up on a given port. If registration is successful, the client will automatically log in for the user to begin playing.
    // Automatically called by connectToMainServer().
    public void signup(int port)
    {
        // Check if user left either field blank.
        if (usernameReg.text.Equals("") || passwordReg.text.Equals(""))
        {
            regFailedMessage.enabled = true;
            return;
        }

        // First, connect to the subserver at the given port.
        Socket cnxn        = null;
        bool   acctCreated = false;

        try {
            cnxn = new Socket(ip, port);
            ObjectOutputStream output = new ObjectOutputStream(cnxn.getOutputStream());

            // Send handshake
            output.writeInt(handshake);
            output.flush();

            // Now that we have connected and sent our handshake, we can send commands.
            // Here we will just sign up, close the connection, and log in using the given name and PW.

            output.writeInt(SIGNUP);
            output.flush();

            // Send username and PW.
            output.writeObject(usernameReg.text);
            output.flush();

            output.writeObject(passwordReg.text);
            output.flush();

            // Check if acc was created
            ObjectInputStream input = new ObjectInputStream(cnxn.getInputStream());
            cnxn.setSoTimeout(10000);
            acctCreated = input.readInt() == SPU.ServerResponse.ACCOUNT_CREATE_OK.ordinal();
            if (!acctCreated)
            {
                // Display an error message if registration failed.
                StartMenuScript sms = (StartMenuScript)(startMenu.GetComponent(typeof(StartMenuScript)));
                sms.RaiseErrorWindow("Account creation failed. That name may already be taken.");
            }

            // At this point, the user is (hopefully) signed up for the server on the given port. So, log in.
            // (Close connection and streams first!)
            output.close();
            input.close();
            cnxn.close();
            regFailedMessage.enabled = false;

            // If registration succeeded, at this point the client will auto-login and start playing the game.
            if (acctCreated)
            {
                usernameLogin.text = usernameReg.text;
                passwordLogin.text = passwordReg.text;
                ((StartMenuScript)(startMenu.GetComponent(typeof(StartMenuScript)))).RegToLogin();
                loginAndPlay(port);
            }
        }catch (java.lang.Exception e) {
            // Display some kind of error window if there was a connection error (basically a Java exception).
            // If the socket is null, the connection attempt failed; otherwise, the connection timed out, or something else happened.
            StartMenuScript sms = (StartMenuScript)(startMenu.GetComponent(typeof(StartMenuScript)));
            if (cnxn == null)
            {
                sms.RaiseErrorWindow("Failed to connect. Check your connection settings. The subserver may be down.");
            }
            else if (e.GetType() == typeof(SocketTimeoutException) && !acctCreated)
            {
                sms.RaiseErrorWindow("Connection timed out. Check your connection. The subserver may have gone down.");
            }
            else if (acctCreated)
            {
                sms.RaiseErrorWindow("Connection timed out, but registration was successful. The subserver may have gone down suddenly.");
            }
            else
            {
                sms.RaiseErrorWindow("An unknown exception occurred when trying to connect to the main server.");
            }
        }catch (System.Exception e) {
            // This handles C# exceptions. These shouldn't happen, which is why the errors are printed to the console (for us to test for ourselves).
            print("Encountered a C# exception:\n");
            print(e.StackTrace);
        }
    }
예제 #23
0
    // This method allows the user to log in and play (if login is successful). Automatically called by either connectToMainServer() or signup().
    public void loginAndPlay(int port)
    {
        // Check if user left either field blank.
        if (usernameLogin.text.Equals("") || passwordLogin.text.Equals(""))
        {
            loginErrorMessage.enabled = true;
            return;
        }

        // First, connect to the subserver at the given port.
        Socket cnxn         = null;
        bool   playerInGame = false;       // tracks whether the player is in-game (i.e. not in the main menu)

        try {
            cnxn = new Socket(ip, port);
            ObjectOutputStream output = new ObjectOutputStream(cnxn.getOutputStream());

            // Send handshake
            output.writeInt(handshake);
            output.flush();

            // Now that we have connected and sent our handshake, we can send commands.
            // First: log in.
            output.writeInt(LOGIN);
            output.flush();

            output.writeObject(usernameLogin.text);
            output.flush();

            output.writeObject(passwordLogin.text);
            output.flush();

            // Check if login was successful or failed
            ObjectInputStream input = new ObjectInputStream(cnxn.getInputStream());
            cnxn.setSoTimeout(10000);
            if (input.readInt() != SPU.ServerResponse.LOGIN_OK.ordinal())
            {
                // Login failed at this point. Disconnect from the server so the user can try again.
                loginErrorMessage.enabled = true;
                output.writeInt(DISCONNECT);
                output.flush();
                input.close();
                output.close();
                cnxn.close();
                return;
            }
            // At this point, login was successful.
            ((StartMenuScript)(startMenu.GetComponent(typeof(StartMenuScript)))).saveLogin();
            loginErrorMessage.enabled = false;

            // Need to get the map first so the user can see stuff. First send the command, then receive the map and visibility.
            output.writeInt(GETCOND);
            output.flush();

            int          visibility = input.readInt();
            SPU.Tile[][] map        = (SPU.Tile[][])(input.readObject());

            // Load the game and start necessary threads.
            isLoading = true;
            StartCoroutine("LoadGame");
            while (isLoading)
            {
                ;
            }
            playerInGame = true;
            Destroy(GameObject.Find("Login Menu"));
            Destroy(GameObject.Find("Registration Menu"));
            Destroy(GameObject.Find("Main Menu Music"));

            // Create a thread to process user inputs (i.e. for the menu and for player movement)
            userInputThread = new System.Threading.Thread(new ThreadStart(new UserInputThread().ProcessInput));
            userInputThread.Start();
            while (!userInputThread.IsAlive)
            {
                ;                                         //loop until thread activates
            }
            // TO DO MUCH LATER: Draw the map, using visibility to determine visible tiles, and put this in the new scene.

            // At this point, process move commands one at a time (or logout if the user chooses).

            while (cmd != LOGOUT)
            {
                // First write the command...
                output.writeInt(cmd);
                output.flush();
                // ...then receive the updated visibility and map from the server.
                visibility = input.readInt();
                map        = (SPU.Tile[][])(input.readObject());
            }

            // At this point, user is ready to log out (cmd == LOGOUT).
            output.writeInt(LOGOUT);
            output.flush();

            // The game can just exit everything completely if the user is quitting to desktop.
            if (isQuitting)
            {
                Application.Quit();
            }

            input.close();
            output.close();
            cnxn.close();
            Destroy(GameObject.Find("BG Music"));
            isLoading = true;
            StartCoroutine("LoadMainMenu");
            while (isLoading)
            {
                ;
            }
            Destroy(this);
        }catch (java.lang.Exception e) {
            // Deal with a failed connection attempt
            StartMenuScript sms = (StartMenuScript)(startMenu.GetComponent(typeof(StartMenuScript)));
            if (cnxn == null)
            {
                sms.RaiseErrorWindow("Failed to connect. Check your connection settings. The subserver may be down.");
            }
            else if (e.GetType() == typeof(SocketTimeoutException) && !playerInGame)
            {
                sms.RaiseErrorWindow("Connection timed out. Check your connection. The subserver may have gone down.");
            }
            else
            {
                // Return to the main menu, since connection has timed out.
                Destroy(startMenu);
                Destroy(GameObject.Find("BG Music"));
                userInputThread.Abort();
                userInputThread.Join();
                isLoading = true;
                StartCoroutine("LoadMainMenu");
                while (isLoading)
                {
                    ;
                }
                StartMenuScript sms2 = ((StartMenuScript)(GameObject.Find("Start Menu").GetComponent <StartMenuScript>()));
                sms2.RaiseErrorWindow("Connection timed out. Check your connection. The subserver may have gone down.");
                Destroy(this);
            }
        }catch (System.Exception e) {
            // This handles C# exceptions. These shouldn't happen, which is why the errors are printed to the console (for us to test for ourselves).
            print("Encountered a C# exception:\n");
            print(e.StackTrace);
        }
    }