Search Results

Search found 70 results on 3 pages for 'objectinputstream'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • Reuse Client java Socket in a Java Server

    - by user1394983
    I'm devoloping an Java server two control an android online game. It's possible save the client socket of myserversocket.accept() in a variable in Client class? This are very util because this way, server can communicate with client when server wants and no when client contact server. My actual code are: import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.UUID; import sal.app.shared.Packet; public class Server { private ArrayList<GameSession> games = new ArrayList<GameSession>(); private ArrayList<Client> pendent_clients = new ArrayList<Client>(); private Packet read_packet= new Packet(); private Packet sent_packet = new Packet(); private Socket clientSocket = null; public static void main(String[] args) throws ClassNotFoundException{ ServerSocket serverSocket = null; //DataInputStream dataInputStream = null; //DataOutputStream dataOutputStream = null; ObjectOutputStream oos=null; ObjectInputStream ois=null; Server myServer = new Server(); try { serverSocket = new ServerSocket(7777); System.out.println("Listening :7777"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } while(true){ try { myServer.clientSocket = new Socket(); myServer.clientSocket = serverSocket.accept(); myServer.read_packet = new Packet(); myServer.sent_packet = new Packet(); oos = new ObjectOutputStream(myServer.clientSocket.getOutputStream()); ois = new ObjectInputStream(myServer.clientSocket.getInputStream()); //dataInputStream = new DataInputStream(clientSocket.getInputStream()); //dataOutputStream = new DataOutputStream(clientSocket.getOutputStream()); //System.out.println("ip: " + clientSocket.getInetAddress()); //System.out.println("message: " + ois.read()); //dataOutputStream.writeUTF("Hello!"); /*while ((myServer.read_packet = (Packet) ois.readObject()) != null) { myServer.handlePacket(myServer.read_packet); break; }*/ myServer.read_packet=(Packet) ois.readObject(); myServer.handlePacket(myServer.read_packet); //oos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if( myServer.clientSocket!= null){ /*try { //myServer.clientSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } /*if( ois!= null){ try { ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if( oos!= null){ try { oos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ } } } public void handlePacket(Packet hp) throws IOException { if(hp.getOpCode() == 1) { registPlayer(hp); } } public void registPlayer(Packet p) throws IOException { Client registClient = new Client(this.clientSocket); this.pendent_clients.add(registClient); if(pendent_clients.size() == 2) { initAGame(); } else { ObjectOutputStream out=null; Packet to_send = new Packet(); to_send.setOpCode(4); out = new ObjectOutputStream(registClient.getClientSocket().getOutputStream()); out.writeObject(to_send); } } public void initAGame() throws IOException { Client c1 = pendent_clients.get(0); Client c2 = pendent_clients.get(1); Packet to_send = new Packet(); ObjectOutputStream out=null; GameSession incomingGame = new GameSession(c1,c2); games.add(incomingGame); to_send.setGameId(incomingGame.getGameId()); to_send.setOpCode(5); out = new ObjectOutputStream(c1.getClientSocket().getOutputStream()); out.writeObject(to_send); out = new ObjectOutputStream(c2.getClientSocket().getOutputStream()); out.writeObject(to_send); pendent_clients.clear(); } public Client getClientById(UUID given_id) { for(GameSession gs: games) { if(gs.getClient1().getClientId().equals(given_id)) { return gs.getClient1(); } else if(gs.getClient2().getClientId().equals(given_id)) { return gs.getClient2(); } } return null; } } With this code i got this erros: java.net.SocketException: Broken pipe at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92) at java.net.SocketOutputStream.write(SocketOutputStream.java:136) at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1847) at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1756) at java.io.ObjectOutputStream.writeNonProxyDesc(ObjectOutputStream.java:1257) at java.io.ObjectOutputStream.writeClassDesc(ObjectOutputStream.java:1211) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1395) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158) at java.io.ObjectOutputStream.writeFatalException(ObjectOutputStream.java:1547) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:333) at Server.initAGame(Server.java:146) at Server.registPlayer(Server.java:120) at Server.handlePacket(Server.java:106) at Server.main(Server.java:63) This error ocurre when second client connect and server try to send an Packet to previous client 1 in function initGame() in this code: out = new ObjectOutputStream(c1.getClientSocket().getOutputStream()); out.writeObject(to_send); my android code is this: package sal.app; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import sal.app.logic.DataBaseManager; import sal.app.shared.Packet; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class MultiPlayerWaitActivity extends Activity{ private DataBaseManager db; public void onCreate(Bundle savedInstanceState) { super.requestWindowFeature(Window.FEATURE_NO_TITLE); super.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.multiwaitlayout); db=DataBaseManager.getSalDatabase(this); db.teste(); try { db.createDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Socket socket = null; ObjectOutputStream outputStream = null; ObjectInputStream inputStream = null; //System.out.println("dadadad"); try { socket = new Socket("192.168.1.4", 7777); //Game = new MultiPlayerGame(new ServerManager("192.168.1.66"),new Session(), new Player("")); outputStream = new ObjectOutputStream(socket.getOutputStream()); inputStream = new ObjectInputStream(socket.getInputStream()); //dataOutputStream.writeUTF(textOut.getText().toString()); //textIn.setText(dataInputStream.readUTF()); Packet p = new Packet(); Packet r = new Packet(); p.setOpCode(1); outputStream.writeObject(p); /*try { r=(Packet)inputStream.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //while(true){ //dataInputStream = new DataInputStream(clientSocket.getInputStream()); //dataOutputStream = new DataOutputStream(clientSocket.getOutputStream()); //System.out.println("ip: " + clientSocket.getInetAddress()); //System.out.println("message: " + ois.read()); //dataOutputStream.writeUTF("Hello!"); /*while ((r= (Packet) inputStream.readObject()) != null) { handPacket(r); break; }*/ r=(Packet) inputStream.readObject(); handPacket(r); //oos.close(); //} /*System.out.println(r.getOpCode()); if(r.getOpCode() == 5) { this.finish(); }*/ } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*finally{ if (socket != null){ try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (outputStream != null){ try { outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (inputStream != null){ try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }*/ //catch (ClassNotFoundException e) { // TODO Auto-generated catch block //e.printStackTrace(); //} catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void handPacket(Packet hp) { if(hp.getOpCode() == 5) { this.finish(); } this.finish(); } } Regards

    Read the article

  • java.io.StreamCorruptedException: invalid stream header: 7371007E

    - by Alex
    Hello, this is pprobably a simple question . I got a client Server application which communicate using objects. when I send only one object from the client to server all works well. when I attempt to send several objects one after another on the same stream I get StreamCorruptedException. can some one direct me to the cause of this error . Thanks client write method private SecMessage[] send(SecMessage[] msgs) { SecMessage result[]=new SecMessage[msgs.length]; Socket s=null; ObjectOutputStream objOut =null; ObjectInputStream objIn=null; try { s=new Socket("localhost",12345); objOut=new ObjectOutputStream( s.getOutputStream()); for (SecMessage msg : msgs) { objOut.writeObject(msg); } objOut.flush(); objIn=new ObjectInputStream(s.getInputStream()); for (int i=0;i<result.length;i++) result[i]=(SecMessage)objIn.readObject(); } catch(java.io.IOException e) { alert(IO_ERROR_MSG+"\n"+e.getMessage()); } catch (ClassNotFoundException e) { alert(INTERNAL_ERROR+"\n"+e.getMessage()); } finally { try {objIn.close();} catch (IOException e) {} try {objOut.close();} catch (IOException e) {} } return result; } server read method //in is an inputStream Defined in the server SecMessage rcvdMsgObj; rcvdMsgObj=(SecMessage)new ObjectInputStream(in).readObject(); return rcvdMsgObj; and the SecMessage Class is public class SecMessage implements java.io.Serializable { private static final long serialVersionUID = 3940341617988134707L; private String cmd; //... nothing interesting here , just a bunch of fields , getter and setters }

    Read the article

  • Receiving XML from Actionscript on Servlet - Invalid Stream Header

    - by John Doe
    I have an ActionScript File sending XML to my servlet. I am only getting empty arrays on output. In ActionScript I checked and I am in fact sending the correct XML. Anyone know what Exactly I'm doing wrong? Exception error is: java.io.StreamCorruptedException: invalid stream header package myDungeonAccessor; try { System.out.println("HEADERS: " + request.getHeaderNames()); ObjectInputStream in = new ObjectInputStream(request.getInputStream()); System.out.println(in); ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream()); } catch(Exception e) { e.printStackTrace(); } Exception

    Read the article

  • Android serialization: ImageView

    - by embo
    I have a simple class: public class Ball2 extends ImageView implements Serializable { public Ball2(Context context) { super(context); } } Serialization ok: private void saveState() throws IOException { ObjectOutputStream oos = new ObjectOutputStream(openFileOutput("data", MODE_PRIVATE)); try { Ball2 data = new Ball2(Game2.this); oos.writeObject(data); oos.flush(); } catch (Exception e) { Log.e("write error", e.getMessage(), e); } finally { oos.close(); } } But deserealization private void loadState() throws IOException { ObjectInputStream ois = new ObjectInputStream(openFileInput("data")); try { Ball2 data = (Ball2) ois.readObject(); } catch (Exception e) { Log.e("read error", e.getMessage(), e); } finally { ois.close(); } } fail with error: 03-24 21:52:43.305: ERROR/read error(1948): java.io.InvalidClassException: android.widget.ImageView; IllegalAccessException How deserialize object correctly?

    Read the article

  • How can I determine if a file I want to read from actually exists?

    - by Imray
    I'm learning Java, and I'm trying to write a program that can read from a .ser file, which I've already created with a writeTo method. I want to know a given file exists in the system before I tell the program to read from it. My code looks like this: public boolean readFromSerializedFile(String fileName){ FileInputStream fileInStream = null; ObjectInputStream objectInStream = null; try{ fileInStream = new FileInputStream(fileName); objectInStream = new ObjectInputStream(fileInStream); Is there a simple way I can determine if the file with the name of the parameter exists in the root directory (or wherever else specified)?

    Read the article

  • How can I link two Java serialised objects back together?

    - by Kidburla
    Sometimes (quite a lot, actually) we get a situation in Java where two objects are pointing to the same thing. Now if we serialise these separately it is quite appropriate that the serialised forms have separate copies of the object as it should be possible to open one without the other. However if we now deserialise them both, we find that they are still separated. Is there any way to link them back together? Example follows. public class Example { private static class ContainerClass implements java.io.Serializable { private ReferencedClass obj; public ReferencedClass get() { return obj; } public void set(ReferencedClass obj) { this.obj = obj; } } private static class ReferencedClass implements java.io.Serializable { private int i = 0; public int get() { return i; } public void set(int i) { this.i = i; } } public static void main(String[] args) throws Exception { //Initialise the classes ContainerClass test1 = new ContainerClass(); ContainerClass test2 = new ContainerClass(); ReferencedClass ref = new ReferencedClass(); //Make both container class point to the same reference test1.set(ref); test2.set(ref); //This does what we expect: setting the integer in one (way of accessing the) referenced class sets it in the other one test1.get().set(1234); System.out.println(Integer.toString(test2.get().get())); //Now serialise the container classes java.io.ObjectOutputStream os = new java.io.ObjectOutputStream(new java.io.FileOutputStream("C:\\Users\\Public\\test1.ser")); os.writeObject(test1); os.close(); os = new java.io.ObjectOutputStream(new java.io.FileOutputStream("C:\\Users\\Public\\test2.ser")); os.writeObject(test2); os.close(); //And deserialise them java.io.ObjectInputStream is = new java.io.ObjectInputStream(new java.io.FileInputStream("C:\\Users\\Public\\test1.ser")); ContainerClass test3 = (ContainerClass)is.readObject(); is.close(); is = new java.io.ObjectInputStream(new java.io.FileInputStream("C:\\Users\\Public\\test2.ser")); ContainerClass test4 = (ContainerClass)is.readObject(); is.close(); //We expect the same thing as before, and would expect a result of 4321, but this doesn't happen as the referenced objects are now separate instances test3.get().set(4321); System.out.println(Integer.toString(test4.get().get())); } }

    Read the article

  • Understanding flow of object creation

    - by Boris Mandovskes
    I'm new to java and I wonder if there is simple way to know flow like the following of object creation, I'm using eclipse and when I write new ObjectInputStream and press CTRL+SPACE. I don't see any option that I can enter new BufferedInputStream (I have copied the code from example) and than to create new object for FileInputStream etc. in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("emp.dat"))); List temp = (List)in.readObject(); I give that example since this is the first time that I saw this kind of creation new object flow and I want to use some best practice for the next times.

    Read the article

  • Send a String[] ArrayList over Socket connection

    - by Duncan Palmer
    So i'm trying to send a String[] Array/List over an open socket connection. I currently have this code: Sending: public void sendData() { try { OutputStream socketStream = socket.getOutputStream(); ObjectOutputStream objectOutput = new ObjectOutputStream(socketStream); objectOutput.writeObject(new String[] {"Test", "Test2", "Test3"}); objectOutput.close(); socketStream.close(); } catch (Exception e) { System.out.println(e.toString()); } } Recieving: public Object readData() { try { InputStream socketStream = socket.getInputStream(); ObjectInputStream objectInput = new ObjectInputStream(new GZIPInputStream(socketStream)); Object a = objectInput.readObject(); return a; } catch(Exception e) { return null; } } After I have recieved the String array/list on the other end I want to be able to iterate through it like I would do normally so I can get the values. My current code doesn't seem to works as it returns null as the value. is this possible?

    Read the article

  • Java - ClassNotFoundException I have the class included, but why do I get an exception?

    - by aloh
    public static Reservation[] openBinaryFile( String fileName ) { Reservation [] objArray = null; try { ObjectInputStream inStream = new ObjectInputStream( new FileInputStream( fileName ) ); objArray = (Reservation[])inStream.readObject(); inStream.close(); } catch( ClassNotFoundException e ) { System.out.println( "Exception: ClassNotFoundException." ); } I have the class included, but why do I get an exception? The class is in the same package as the others. Why am I getting this exception?

    Read the article

  • Too much delay while sending object over UDP to server

    - by RomZes
    I'm getting 4 sec delay when sending objects over UDP. Working on small game and trying to implement multiplayer. For now just trying to synchronize movements of 2 balls on the screen. StartingPoint.java is my server(first player), that receiving serialized objects (coordinates). SecondPlayer.java is client that sending serialized objects to server. When I'm moving my first object it appears 4 seconds later on different screen. StartingPoint.java @Override public void run() { byte[] receiveData = new byte[256]; byte[] sendData = new byte[256]; // DatagramSocket socketS; try { socket = new DatagramSocket(5000); System.out.println("Socket created on "+ port + " port"); } catch (SocketException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } while(true){ b1.update(this); b3.update(); System.out.println("Starting server..."); //// Receiving and deserializing object try { //socket.setSoTimeout(1000); DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); byte[] data = packet.getData(); ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); // socket.setSoTimeout(300); b1 = (Ball) is.readObject(); } catch (IOException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } repaint(); try { Thread.sleep(17); } catch (InterruptedException e) { e.printStackTrace(); } SecondPlayer.java @Override public void run() { while(true){ b.update(); networkSend(); repaint(); try { Thread.sleep(17); } catch (InterruptedException e) { e.printStackTrace(); } } public void networkSend(){ // Serialize to a byte array try { ByteArrayOutputStream bStream = new ByteArrayOutputStream(); ObjectOutputStream oo; oo = new ObjectOutputStream(bStream); oo.writeObject(b); oo.flush(); oo.close(); byte[] bufCar = bStream.toByteArray(); //socket = new DatagramSocket(); //socket.setSoTimeout(1000); InetAddress address = InetAddress.getByName("localhost"); DatagramPacket packet = new DatagramPacket(bufCar, bufCar.length, address, port); socket.send(packet); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

    Read the article

  • Java game applet development

    - by RomZes
    I'm getting 4 sec delay when sending objects over UDP. Working on small game and trying to implement multiplayer. For now just trying to synchronize movements of 2 balls on the screen. StartingPoint.java is my server(first player), that receiving serialized objects (coordinates). SecondPlayer.java is client that sending serialized objects to server. When I'm moving my first object it appears 4 seconds later on different screen. StartingPoint.java @Override public void run() { byte[] receiveData = new byte[256]; byte[] sendData = new byte[256]; // DatagramSocket socketS; try { socket = new DatagramSocket(5000); System.out.println("Socket created on "+ port + " port"); } catch (SocketException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } while(true){ b1.update(this); b3.update(); System.out.println("Starting server..."); //// Receiving and deserializing object try { //socket.setSoTimeout(1000); DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); byte[] data = packet.getData(); ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); // socket.setSoTimeout(300); b1 = (Ball) is.readObject(); } catch (IOException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } repaint(); try { Thread.sleep(17); } catch (InterruptedException e) { e.printStackTrace(); } SecondPlayer.java @Override public void run() { while(true){ b.update(); networkSend(); repaint(); try { Thread.sleep(17); } catch (InterruptedException e) { e.printStackTrace(); } } public void networkSend(){ // Serialize to a byte array try { ByteArrayOutputStream bStream = new ByteArrayOutputStream(); ObjectOutputStream oo; oo = new ObjectOutputStream(bStream); oo.writeObject(b); oo.flush(); oo.close(); byte[] bufCar = bStream.toByteArray(); //socket = new DatagramSocket(); //socket.setSoTimeout(1000); InetAddress address = InetAddress.getByName("localhost"); DatagramPacket packet = new DatagramPacket(bufCar, bufCar.length, address, port); socket.send(packet); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

    Read the article

  • easiest and best way to make a server queue java

    - by houlahan
    i have a server at the moment which makes a new thread for every user connected but after about 6 people are on the server for more than 15 mins it tends to flop and give me java heap out of memory error i have 1 thread that checks with a mysql database every 30 seconds to see if any of the users currently logged on have any new messages. what would be the easiest way to implement a server queue? this is the my main method for my server: public class Server { public static int MaxUsers = 1000; //public static PrintStream[] sessions = new PrintStream[MaxUsers]; public static ObjectOutputStream[] sessions = new ObjectOutputStream[MaxUsers]; public static ObjectInputStream[] ois = new ObjectInputStream[MaxUsers]; private static int port = 6283; public static Connection conn; static Toolkit toolkit; static Timer timer; public static void main(String[] args) { try { conn = (Connection) Mysql.getConnection(); } catch (Exception ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("****************************************************"); System.out.println("* *"); System.out.println("* Cloud Server *"); System.out.println("* ©2010 *"); System.out.println("* *"); System.out.println("* Luke Houlahan *"); System.out.println("* *"); System.out.println("* Server Online *"); System.out.println("* Listening On Port " + port + " *"); System.out.println("* *"); System.out.println("****************************************************"); System.out.println(""); mailChecker(); try { int i; ServerSocket s = new ServerSocket(port); for (i = 0; i < MaxUsers; ++i) { sessions[i] = null; } while (true) { try { Socket incoming = s.accept(); boolean found = false; int numusers = 0; int usernum = -1; synchronized (sessions) { for (i = 0; i < MaxUsers; ++i) { if (sessions[i] == null) { if (!found) { sessions[i] = new ObjectOutputStream(incoming.getOutputStream()); ois[i]= new ObjectInputStream(incoming.getInputStream()); new SocketHandler(incoming, i).start(); found = true; usernum = i; } } else { numusers++; } } if (!found) { ObjectOutputStream temp = new ObjectOutputStream(incoming.getOutputStream()); Person tempperson = new Person(); tempperson.setFlagField(100); temp.writeObject(tempperson); temp.flush(); temp = null; tempperson = null; incoming.close(); } else { } } } catch (IOException ex) { System.out.println(1); Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } } catch (IOException ex) { System.out.println(2); Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } public static void mailChecker() { toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new mailCheck(), 0, 10 * 1000); } }

    Read the article

  • Sending XML to Servlet from Action Script

    - by John Doe
    I am only getting empty arrays on output. Anyone know what Exactly I'm doing wrong? package myDungeonAccessor; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class myDungeonAccessorServlet extends HttpServlet { private myDungeonAccessor dataAccessor; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { /* TODO output your page here out.println("<html>"); out.println("<head>"); out.println("<title>Servlet myDungeonAccessorServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet myDungeonAccessorServlet at " + request.getContextPath () + "</h1>"); out.println("</body>"); out.println("</html>"); */ } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); // PrintWriter out = response.getWriter(); System.out.println("yo mom"); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //System.out.println("heppo"); //dataAccessor = new myDungeonAccessor(); System.out.println("Hello"); try { System.out.println("HEADERS: " + request.getHeaderNames()); ObjectInputStream in = new ObjectInputStream(request.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream()); } catch(Exception e) { e.printStackTrace(); } System.out.println("WAZZUP"); byte [] buffer = new byte[4096]; //in.read(buffer); System.out.println("TEST!"); String s = new String(buffer); System.out.println("Update S:" + s); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; } }

    Read the article

  • Android Hashtable Serialization

    - by Nsyed
    Hi All, I am having a weird issue with serialization of a Hashtable. I have made a Server, Client app. Where server(PC/MAC) is serializing a Hashtable and sending it to Client(Android) through UDP. The data is sent/read correctly but I get a bunch of these messages below on LogCat. 04-12 11:19:43.059: DEBUG/dalvikvm(407): GetFieldID: unable to find field Ljava/util/Hashtable;.loadFactor:F Occasionally, I would see these 04-12 11:21:19.150: DEBUG/dalvikvm(407): GC freed 10814 objects / 447184 bytes in 97ms The app would run for 2-3 mins and then crash. Interestingly enough I do not see the Loadfactor errors on SDK 1.5. But I do see the GC Free xxxx objects, quiet often. After debugging I have found that the issue is with de-serialization and the error/warning are coming from following code Code: ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); object = ois.readObject(); at Code: object = ois.readObject(); on the client. My server is serializing code is the following. Code: ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(obj); Any idea what is going on? Thanks for the Help!

    Read the article

  • Variable reference problem when loading an object from a file in Java

    - by Snail
    I have a problem with the reference of a variable when loading a saved serialized object from a data file. All the variables referencing to the same object doesn't seem to update on the change. I've made a code snipped below that illustrates the problem. Tournament test1 = new Tournament(); Tournament test2 = test1; try { FileInputStream fis = new FileInputStream("test.out"); ObjectInputStream in = new ObjectInputStream(fis); test1 = (Tournament) in.readObject(); in.close(); } catch (IOException ex){ Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex){ Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("test1: " + test1); System.out.println("test2: " + test2); After this code is ran test1 and test2 doesn't reference to the same object anymore. To my knowledge they should do that since in the declaration of test2 makes it a reference to test1. When test1 is updated test2 should reflect the change and return the new object when called in the code. Am I missing something essential here or have I been misstaught about how the variable references in Java works?

    Read the article

  • using Object input\ output Streams with files and array list

    - by soad el-hayek
    hi every one .. i'm an it student , and it's time to finish my final project in java , i've faced too many problems , this one i couldn't solve it and i'm really ubset ! :S my code is like this : in Admin class : public ArrayList cos_info = new ArrayList(); public ArrayList cas_info = new ArrayList(); public int cos_count = 0 ; public int cas_count = 0 ; void coustmer_acount() throws FileNotFoundException, IOException{ String add=null; do{ person p = new person() ; cos_info.add(cos_count, p); cos_count ++ ; add =JOptionPane.showInputDialog("Do you want to add more coustmer..\n'y'foryes ..\n 'n'for No .."); } while(add.charAt(0) == 'Y'||add.charAt(0)=='y'); writenew_cos(); // add_acounts(); } void writenew_cos() throws IOException{ ObjectOutputStream aa = new ObjectOutputStream(new FileOutputStream("coustmer.txt")); aa.writeObject(cos_info); JOptionPane.showMessageDialog(null,"Added to file done sucessfuly.."); aa.close(); } in Coustmer class : void read_cos() throws IOException, ClassNotFoundException{ person p1= null ; int array_count = 0; ObjectInputStream d = new ObjectInputStream(new FileInputStream("coustmer.txt")); JOptionPane.showMessageDialog(null,d.available() ); for(int i = 0;d.available() == 0;i++){ a.add(array_count,(ArrayList) d.readObject()); array_count++; JOptionPane.showMessageDialog(null,"Haaaaai :D" ); JOptionPane.showMessageDialog(null,array_count ); } d.close(); JOptionPane.showMessageDialog(null,array_count +"1111" ); for(int i = 0 ; i it just print JOptionPane.showMessageDialog(null,d.available() ); and having excep. here a.add(array_count,(ArrayList) d.readObject()); p.s : person object from my own class and it's Serializabled

    Read the article

  • Trouble accessing fields of a serialized object in Java

    - by typoknig
    I have instantized a class that implements Serializable and I am trying to stream that object like this: try{ Socket socket = new Socket("localhost", 8000); ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream()); toServer.writeObject(myObject); } catch (IOException ex) { System.err.println(ex); } All good so far right? Then I am trying to read the fields of that object like this: //This is an inner class class HandleClient implements Runnable{ private ObjectInputStream fromClient; private Socket socket; // This socket was established earlier try { fromClient = new ObjectInputStream(socket.getInputStream()); GetField inputObjectFields = fromClient.readFields(); double myFristVariable = inputObjectFields.get("myFirstVariable", 0); int mySecondVariable = inputObjectFields.get("mySecondVariable", 0); //do stuff } catch (IOException ex) { System.err.println(ex); } catch (ClassNotFoundException ex) { System.err.println(ex); } finally { try { fromClient.close(); } catch (Exception ex) { ex.printStackTrace(); } } } But I always get the error: java.io.NotActiveException: not in call to readObject This is my first time streaming objects instead of primitive data types, what am I doing wrong? BONUS When I do get this working correctly, is the ENTIRE CLASS passed with the serialized object (i.e. will I have access to the methods of the object's class)? My reading suggests that the entire class is passed with the object, but I have been unable to use the objects methods thus far. How exactly do I call on the object's methods? In addition to my code above I also experimented with the readObject method, but I was probably using it wrong too because I couldn't get it to work. Please enlighten me.

    Read the article

  • Adding to existing JList

    - by Máca Danilov
    I need some help about adding items to JList. I work on some "library" kind of project. And I need to add readers to already existing JList. But when I try to add it, JList just resets, removes all the readers and starts adding readers to a new blank JList. But I don't need it to make new list but add it to the already existing one. I know it's something about creating new model after adding, but i don't know where to fix it. panelHorni = new JPanel(); listModel = new DefaultListModel(); listCtenaru = new JList(listModel); FileInputStream fis = new FileInputStream("myjlist.bin"); ObjectInputStream ois = new ObjectInputStream(fis); listCtenaru = (JList)ois.readObject(); listScroll = new JScrollPane(); listScroll.add(listCtenaru); listCtenaru.setPreferredSize(new Dimension(350, 417)); listCtenaru.setBackground(new Color(238,238,238)); panelHorni.add(listCtenaru); listener public void actionPerformed(ActionEvent e) { String jmeno = pole1.getText(); String prijmeni = pole2.getText(); listModel.addElement(jmeno +" "+ prijmeni); listCtenaru.setModel(listModel); pole1.setText(""); pole2.setText(""); pole1.requestFocus();

    Read the article

  • Pass the return type as a parameter in java?

    - by jonderry
    I have some files that contain logs of objects. Each file can store objects of a different type, but a single file is homogeneous -- it only stores objects of a single type. I would like to write a method that returns an array of these objects, and have the array be of a specified type (the type of objects in a file is known and can be passed as a parameter). Roughly, what I want is something like the following: public static <T> T[] parseLog(File log, Class<T> cls) throws Exception { ArrayList<T> objList = new ArrayList<T>(); FileInputStream fis = new FileInputStream(log); ObjectInputStream in = new ObjectInputStream(fis); try { Object obj; while (!((obj = in.readObject()) instanceof EOFObject)) { T tobj = (T) obj; objList.add(tobj); } } finally { in.close(); } return objList.toArray(new T[0]); } The above code doesn't compile (there's an error on the return statement, and a warning on the cast), but it should give you the idea of what I'm trying to do. Any suggestions for the best way to do this?

    Read the article

  • Java JCheckBox ArrayList help needed

    - by user2929626
    I'm new to Java and struggling with something which I'm sure must have a simple answer but I can't seem to find it. I have an array of checkbox objects defined as: ArrayList<JCheckBox> checkBoxList A JPanel is created with a grid layout and the checkboxes are added to the JPanel and the ArrayList: for (int i = 0; i < 256; i++) { JCheckBox c = new JCheckBox(); c.setSelected(false); checkBoxList.add(c); mainPanel.add(c); } Yes, there are 256 checkboxes! The panel is added to a JFrame and eventually the GUI is displayed. The user can select any combination of the 256 checkboxes. My class implements Serializable and this ArrayList of checkboxes can be saved and restored using 'Save' and 'Load' GUI buttons. My code to load the saved object is as below: public class LoadListener implements ActionListener { public void actionPerformed(ActionEvent a) { try { // Prompt the user for a load file JFileChooser fileLoad = new JFileChooser(); fileLoad.showOpenDialog(mainFrame); // Create a object/file input stream linking to the selected file ObjectInputStream is = new ObjectInputStream(new FileInputStream(fileLoad.getSelectedFile())); // Read the checkBox array list checkBoxList = (ArrayList<JCheckBox>) is.readObject(); is.close(); } catch (Exception ex) { ex.printStackTrace(); } } On loading the ArrayList object, the values of the checkboxes are correctly populated, however I want to update the checkboxes on the GUI to reflect this. Is there an easy way to do this? I assumed as the array of checkboxes had the correct values that I could just repaint the panel / frame but this doesn't work. I'd like to understand why - does my loaded array of checkbox objects no longer reflect the checkbox objects on the GUI? Any help would be much appreciated. Thanks!

    Read the article

  • [Java] RSA BadPaddingException : data must start with zero

    - by Robin Monjo
    Hello everyone. I try to implement an RSA algorithm in a Java program. I am facing the "BadPaddingException : data must start with zero". Here are the methods used to encrypt and decrypt my data : public byte[] encrypt(byte[] input) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");// cipher.init(Cipher.ENCRYPT_MODE, this.publicKey); return cipher.doFinal(input); } public byte[] decrypt(byte[] input) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");/// cipher.init(Cipher.DECRYPT_MODE, this.privateKey); return cipher.doFinal(input); } privateKey and publicKey attributes are read from files this way : public PrivateKey readPrivKeyFromFile(String keyFileName) throws IOException { PrivateKey key = null; try { FileInputStream fin = new FileInputStream(keyFileName); ObjectInputStream ois = new ObjectInputStream(fin); BigInteger m = (BigInteger) ois.readObject(); BigInteger e = (BigInteger) ois.readObject(); RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e); KeyFactory fact = KeyFactory.getInstance("RSA"); key = fact.generatePrivate(keySpec); ois.close(); } catch (Exception e) { e.printStackTrace(); } return key; } Private key and Public key are created this way : public void Initialize() throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048); keyPair = keygen.generateKeyPair(); KeyFactory fact = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pub = fact.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class); RSAPrivateKeySpec priv = fact.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class); saveToFile("public.key", pub.getModulus(), pub.getPublicExponent()); saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent()); } and then saved in files : public void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException { FileOutputStream f = new FileOutputStream(fileName); ObjectOutputStream oos = new ObjectOutputStream(f); oos.writeObject(mod); oos.writeObject(exp); oos.close(); } I can't figured out how the problem come from. Any help would be appreciate ! Thanks in advance.

    Read the article

  • Socket server with multiple clients, sending messages to many clients without hurting liveliness

    - by Karl Johanson
    I have a small socket server, and I need to distribute various messages from client-to-client depending on different conditionals. However I think I have a small problem with livelyness in my current code, and is there anything wrong in my approach: public class CuClient extends Thread { Socket socket = null; ObjectOutputStream out; ObjectInputStream in; CuGroup group; public CuClient(Socket s, CuGroup g) { this.socket = s; this.group = g; out = new ObjectOutputStream(this.socket.getOutputStream()); out.flush(); in = new ObjectInputStream(this.socket.getInputStream()); } @Override public void run() { String cmd = ""; try { while (!cmd.equals("client shutdown")) { cmd = (String) in.readObject(); this.group.broadcastToGroup(this, cmd); } out.close(); in.close(); socket.close(); } catch (Exception e) { System.out.println(this.getName()); e.printStackTrace(); } } public void sendToClient(String msg) { try { this.out.writeObject(msg); this.out.flush(); } catch (IOException ex) { } } And my CuGroup: public class CuGroup { private Vector<CuClient> clients = new Vector<CuClient>(); public void addClient(CuClient c) { this.clients.add(c); } void broadcastToGroup(CuClient clientName, String cmd) { Iterator it = this.clients.iterator(); while (it.hasNext()) { CuClient cu = (CuClient)it.next(); cu.sendToClient(cmd); } } } And my main-class: public class SmallServer { public static final Vector<CuClient> clients = new Vector<CuClient>(10); public static boolean serverRunning = true; private ServerSocket serverSocket; private CuGroup group = new CuGroup(); public void body() { try { this.serverSocket = new ServerSocket(1337, 20); System.out.println("Waiting for clients\n"); do { Socket s = this.serverSocket.accept(); CuClient t = new CuClient(s,group); System.out.println("SERVER: " + s.getInetAddress() + " is connected!\n"); t.start(); } while (this.serverRunning); } catch (IOException ex) { ex.printStackTrace(); } } public static void main(String[] args) { System.out.println("Server"); SmallServer server = new SmallServer(); server.body(); } } Consider the example with many more groups, maybe a Collection of groups. If they all synchronize on a single Object, I don't think my server will be very fast. I there a pattern or something that can help my liveliness?

    Read the article

  • Complex HashMap has different hashCode after serialization

    - by woezelmann
    I am parsing a xml file into a complex HashMap looking like this: Map<String, Map<String, EcmObject> EcmObject: public class EcmObject implements Comparable, Serializable { private final EcmObjectType type; private final String name; private final List<EcmField> fields; private final boolean pages; // getter, equals, hashCode } EcmObjectType: public enum EcmObjectType implements Serializable { FOLDER, REGISTER, DOCUMENT } EcmField public class EcmField implements Comparable, Serializable { private final EcmFieldDataType dataType; private final EcmFieldControlType controlType; private final String name; private final String dbname; private final String internalname; private final Integer length; // getter, equals, hashCode } EcmFieldDataType public enum EcmFieldDataType implements Serializable { TEXT, DATE, NUMBER, GROUP, DEC; } and EcmFieldControlType public enum EcmFieldControlType implements Serializable{ DEFAULT, CHECKBOX, LIST, DBLIST, TEXTAREA, HIERARCHY, TREE, GRID, RADIO, PAGECONTROL, STATIC; } I have overwritten all hashCode and equal methods by usind commons lang's EqualsBuilder and HashCodeBuilder. Now when I copy a A HashMap this way: Map<String, Map<String, EcmObject>> m = EcmUtil.convertXmlObjectDefsToEcmEntries(new File("e:\\objdef.xml")); Map<String, Map<String, EcmObject>> m2; System.out.println(m.hashCode()); ByteArrayOutputStream baos = new ByteArrayOutputStream(8 * 4096); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(m); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); m2 = (Map<String, Map<String, EcmObject>>) ois.readObject(); System.out.println(m.hashCode()); System.out.println(m2.hashCode()); m.hashCode() is not equal to m2.hashCode() here is my output: -1639352210 -2071553208 1679930154 Another strange thing is, that eg. 10 times m has the same hashcode and suddenly on the 11th time the hashcode is different... Any ideas what this is about?

    Read the article

  • Blob object not working properly even though the class is seralized

    - by GustlyWind
    I have class which is seralized and does convert a very large amount of data object to blob to save it to database.In the same class there is decode method to convert blob to the actual object.Following is the code for encode and decode of the object. private byte[] encode(ScheduledReport schedSTDReport) { byte[] bytes = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(schedSTDReport); oos.flush(); oos.close(); bos.close(); //byte [] data = bos.toByteArray(); //ByteArrayOutputStream baos = new ByteArrayOutputStream(); //GZIPOutputStream out = new GZIPOutputStream(baos); //XMLEncoder encoder = new XMLEncoder(out); //encoder.writeObject(schedSTDReport); //encoder.close(); bytes = bos.toByteArray(); //GZIPOutputStream out = new GZIPOutputStream(bos); //out.write(bytes); //bytes = bos.toByteArray(); } catch (Exception e) { _log.error("Exception caught while encoding/zipping Scheduled STDReport", e); } decode(bytes); return bytes; } /* * Decode the report definition blob back to the * ScheduledReport object. */ private ScheduledReport decode(byte[] bytes) { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ScheduledReport sSTDR = null; try { ObjectInputStream ois = new ObjectInputStream(bais); //GZIPInputStream in = new GZIPInputStream(bais); //XMLDecoder decoder = new XMLDecoder(in); sSTDR = (ScheduledReport)ois.readObject();//decoder.readObject(); //decoder.close(); } catch (Exception e) { _log.error("IOException caught while decoding/unzipping Scheduled STDReport", e); } return sSTDR; } The problem here is whenver I change something else in this class means any other method,a new class version is created and so the new version the class is unable to decode the originally encoded blob object. The object which I am passing for encode is also seralized object but this problem exists. Any ideas thanks

    Read the article

  • readObject() vs. readResolve() to restore transient fields

    - by Joonas Pulakka
    According to Serializable javadoc, readResolve() is intended for replacing an object read from the stream. But is it OK to use it for restoring transient fields, like so: private Object readResolve() { transientField = something; return this; } as opposed to using readObject(): private void readObject(ObjectInputStream s) { s.defaultReadObject(); transientField = something; } Is there any reason to choose one over other, when used to just restore transient fields?

    Read the article

< Previous Page | 1 2 3  | Next Page >