// 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); } }
/// <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) { } } } }
//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(); } }
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(); }
//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()); }
//-------------------------------------------------------------------------------------------------- /// <summary> /// Serializes and deserializes an array using default serialization. /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static MultiCurrencyAmountArray serializedDeserialize(MultiCurrencyAmountArray array) throws Exception private static MultiCurrencyAmountArray serializedDeserialize(MultiCurrencyAmountArray array) { MemoryStream byteOutputStream = new MemoryStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream); objectOutputStream.writeObject(array); objectOutputStream.flush(); MemoryStream byteInputStream = new MemoryStream(byteOutputStream.toByteArray()); ObjectInputStream objectInputStream = new ObjectInputStream(byteInputStream); return((MultiCurrencyAmountArray)objectInputStream.readObject()); }
/** * 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); }
/** * Creates a new area code map serializing the provided area code map to a stream and then reading * this stream. The resulting area code map is expected to be strictly equal to the provided one * from which it was generated. */ private static AreaCodeMap createNewAreaCodeMap(AreaCodeMap areaCodeMap) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); areaCodeMap.writeExternal(objectOutputStream); objectOutputStream.flush(); AreaCodeMap newAreaCodeMap = new AreaCodeMap(); newAreaCodeMap.readExternal( new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()))); return(newAreaCodeMap); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void write(String inputFile, com.juliar.codegenerator.InstructionInvocation invocation) throws IOException public virtual void write(string inputFile, InstructionInvocation invocation) { string fileName = getLibiraryName(inputFile); try (OutputStream ostream = new FileOutputStream(fileName); ObjectOutputStream p = new ObjectOutputStream(ostream) ) { p.writeObject(invocation); p.flush(); } catch (IOException e) { JuliarLogger.log(e); } }
[TestMethod] public void testReadWriteExternal() { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); mappingProvider.writeExternal(objectOutputStream); objectOutputStream.flush(); MappingFileProvider newMappingProvider = new MappingFileProvider(); newMappingProvider.readExternal( new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()))); assertEquals(mappingProvider.toString(), newMappingProvider.toString()); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage()); fail(); } }
[TestMethod] public void testReadExternalThrowsIOExceptionWithMalformedData() { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeUTF("hello"); objectOutputStream.flush(); ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); FlyweightMapStorage newMapStorage = new FlyweightMapStorage(); try { newMapStorage.readExternal(objectInputStream); fail(); } catch (IOException) { // Exception expected. } }
[TestMethod] public void testWriteAndReadExternal() { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); mapStorage.writeExternal(objectOutputStream); objectOutputStream.flush(); FlyweightMapStorage newMapStorage = new FlyweightMapStorage(); ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); newMapStorage.readExternal(objectInputStream); String expected = mapStorage.toString(); assertEquals(expected, newMapStorage.toString()); }
/// <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) { } } } }
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(); }
public override void close() { output.flush(); output.close(); }
// 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); } }
// 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); } }