Open an objectoutputstream and printwriter on socket

I have the following code:
public void openConnection(String ipAddress) throws ConnectException{
try{
      client = new Socket(ipAddress, 2000);
     out = new PrintWriter(client.getOutputStream(), true);
      objectOut = new ObjectOutputStream(client.getOutputStream());
     in = new ObjectInputStream(client.getInputStream());
     catch(ConnectException e){
     //there is no securityservice on the other side
     throw new ConnectException();}
     catch(Exception e){
               System.out.println("Error : " +e);
* Method that sends a list of constraints to the peer service
* @param: SecurityConstraintList list: the list of constraints that is being sent to the peer
* @param: String origin: the IP address of the sender, the peer uses this to save the list
public void sendConstraints(SecurityConstraintList list, String origin){
try{     out.println(origin);
     out.println("list");
     out.flush();
     objectOut.writeObject(list);
     objectOut.flush();
     in.close();
     objectOut.close();
     out.close();
catch(Exception e){
     System.out.println("Error : "+e.getMessage());
     }The problem is situated in the part where I first print a line to the printwriter and after an object to the objectoutputstream. On the server i get an exception, being OptionalDataException.
I don't get what the problem is. The exception is thrown when he reads information that he didn't expected, but i don't see how this is possible? Part of the code on the serverside is:
else{
     if( inputLine.equals("list") ){
     //it is a securityconstraintlist that is sent
     SecurityConstraintList list;
     list = (SecurityConstraintList)inObject.readObject();
     System.out.println("Saving list");
     AppliedConstraints con = new AppliedConstraints(origin,list);
FileOutputStream fileOutputStream = new FileOutputStream(listFile);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOutputStream);     objectOut.writeObject(con);
     objectOut.flush();                    
     objectOut.close();
     fileOutputStream.close();
     }Is it not possible to open an objectoutputstream and printwriter on the same outputstream? If so, is there an (easy) way to work around this?
Any help would be greatly appreciated.

Not sure what you mean by this 'reading those line
terminators' ? Could you clarify?In your code I see a 'out.println("list");' statement. This sends the following character over your socket -- 'l', 'i', 's', 't', '\r', '\n', where the last characters denote a carriage return and a new line character respectively. Suppose the receiving en of the socket happens to be a Mac, where a line terminator is implemented as a single '\r'. This leaves the following '\n' character unread and ready to be read by the ObjectInputStream, which, obviously, doesn't know how to handle primitive data like this (hence the OptionalDataException).
Like I wrote before -- read those individual bytes and see what really is transmitted over that socket; there must be some spurious bytes in there ...
kind regards,
Jos

Similar Messages

  • How to solve the exception with socket and PrintWriter constructor

    I am working on a socket communication program and everything works fine on my computer until my boss moved my code to his computer. The following is the client code.
    The client program terminate with exception "Couldn't get I/O for the connection to local host." I have no idea how to solve the problem because there is no way out if the two statements (socket constructor and PrintWriter) fail.
    /*the program shall close connections and exit if the user clicks 'e'.*/
    public class LocalClient extends JPanel implements KeyListener {
    Socket localSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    char fromServer = ' ';
    public LocalClient() {
    try {
    localSocket = new Socket("a029243.cs.uregina.ca", 4444);
    out = new PrintWriter(localSocket.getOutputStream(), true);
    } catch (UnknownHostException e) {
    System.err.println("Don't know about local host.");
    System.exit(1);
    } catch (IOException e) {
    System.err.println("Couldn't get I/O for the connection to
    local host.");
    System.exit(1);
    addKeyListener(this);
    }//end of constructor
    /*the component needs to be focused in order to respond to user input */
    public boolean isFocusTraversable() {return true;}
    public void keyPressed(KeyEvent evt) {
    public void keyReleased (KeyEvent evt) {
    public void keyTyped(KeyEvent evt) {
    System.out.println("key typed is called ");
    char fromClient=evt.getKeyChar();
    if (fromClient!= ' ') {
    if (fromClient=='e')
    try {
    out.close();
    localSocket.close();
    System.exit(1);
    } catch (IOException e)
    {System.out.println("connection closed");}
    else {
    System.out.println("Client: " +
    fromClient);
    out.println(fromClient);
    out.flush();}
    public static void main(String[] args) throws IOException {
    JFrame frame1=new JFrame();
    Container contentPane=frame1.getContentPane();
    LocalClient lc = new LocalClient();
    contentPane.add(lc);
    frame1.pack();
    frame1.setSize(50,50);
    frame1.setVisible(true);
    }//end of main
    } //end of class

    Add e.printStackTrace() or System.out.println(e) to the catch block of the IOException. The IOException has a message about what went wrong.

  • Open an input stream to a socket

    How many times I can open an input stream to a socket? If I create more than one an input stream to a socket, does this affect anything?
    Thanks.

    Generally low level classes do not have high level logic. Socket is a low level class, it's only logic is to connect you to something, and allow you to read and write to that thing (through the socket) using streams. Being able to connect multiple times or setting marks on your stream is a higher level of logic. Putting to much logic is low level classes tends to reduce re-useablility (making unmarkable streams markable as nothing to do with sockets and can be re-used upon any streams that do not support to be marked) and sometimes performances (having marks means having a buffer means having a potential big memory allocation in your Socket that you do not control).
    So in your case, since you are not really interested in re-connecting a socket, you should rather go for a wrapping InputStream that provides marking capabilities over the streams used by the socket class itself.
       Socket socket = getSocket();
       // this one does not support to be marked
       InputStream stream = socket.getInputStream();
       // but now it does :)
       stream = new BufferedInputStream( stream );

  • Basic Java Help (BufferedReader and PrintWriter)

    I am studying Java for part of my degree and have become quite stuck on a question. I have set up a seperate client class and that appears to work just fine, yet when i come to set up the server class i encounter no end of problems.
    Firstly i have to set up a Server class which handles the communication to the client ;
    import java.net.*;
    import java.io.*;
    public class Server
    private ServerSocket ss;
    private Socket socket;
    //Streams for connections
    private InputStream is;
    private OutputStream os;
    //Writer and reader for communication
    private PrintWriter toClient;
    private BufferedReader fromClient;
    private GameSession game;
    //use a high numbered non-dedicated port
    static final int PORT_NUMBER = 3000;
    //set up socket communication
    public Server() throws IOException
    ss = new ServerSocket(PORT_NUMBER);
    //accept a player connection
    public void acceptPlayer()
    System.out.println("Waiting for player");
    //wait for and accept a player
    try
    while(true)
    //Loop endlessly waiting for client connections
    // Wait for a connection request
    socket = ss.accept();
    openStreams();
    //Client has connected
    game.run(); <-- this i presume runs the method run() from the GameSession Class?
    closeStreams();
    socket.close();
    catch(Exception e)
    System.out.println("Trouble with a connection "+ e);
    private void openStreams() throws IOException
    final boolean AUTO_FLUSH = true;
    is = socket.getInputStream();
    fromClient = new BufferedReader(new InputStreamReader(is));
    os = socket.getOutputStream();
    toClient = new PrintWriter(os, AUTO_FLUSH);
    System.out.println ("...Streams set up");
    private void closeStreams() throws IOException
    toClient.close();
    os.close();
    fromClient.close();
    is.close();
    System.out.println("...Streams closed down");
    // This is the top-level method to handle one game
    public void run() throws IOException
    game = new GameSession(socket);
    acceptPlayer();
    System.out.println("Server closing down");
    } // end class
    which also seems to be about what the question asks, yet i have to link this to the GameSession class sending it a reference of the socket. Which i think i have with the inclusion of the new GameSession(socket).
    When i come to write the GameSession class i realise i have to use the BufferedReader and PrintWriter when i try and do this i get a bindException as obviously the port is up and running from the Server class.
    I have tried incorporating the openStreams() in the GameSession after rermoving them from the Server class but get more Exceptions! What am i doing wron and where would i find more information on this?
    Thanks for any help you may give.

    You must redesign your Server and GameSession class.
    Study this code:
    /* save and compile as GameServer.java */
    import java.net.*;
    import java.io.*;
    public class GameServer{
      static final int PORT_NUMBER = 3000;
      private ServerSocket ss;
      GameSession game;
      public GameServer() throws IOException{
        ss = new ServerSocket(PORT_NUMBER);
        game = new GameSession();
      public void acceptPlayer(){
        System.out.println("Waiting for player");
        try{
          while(true){
            Socket s = ss.accept();
            new Thread(new ClientHandler(s)).start();
        catch(Exception e){
          System.out.println("Trouble with a connection "+ e);
      public static void main(String[] args){
        try{
          GameServer gs = new GameServer();
          gs.acceptPlayer();
        catch (Exception e){
          e.printStackTrace();
      class ClientHandler implements Runnable{
        private Socket socket;
        private PrintWriter toClient;
        private BufferedReader fromClient;
        public ClientHandler(Socket sc){
          socket = sc;
          try{
            fromClient
              = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            toClient = new PrintWriter(socket.getOutputStream(), true);
          catch (Exception e){
            e.printStackTrace();
        public void run() throws IOException{
          game.addNewClient(socket, fromClient, toClient);
    }

  • When i login to my mac, it opens iTunes, Skype and AIM. I've tried deleting these from the login items, but they are not on the list.  Can anyone help?

    When i login to my mac, it opens iTunes, Skype and AIM. I've tried deleting these from the login items, but they are not on the list.  Can anyone help?

    babowa wrote:
    If you do not lock that folder immediately after deleting all the contents, it will simply populate again (Resume - a "feature" in Lion). You do that by doing a Get Info (highlight folder and press Command + I keys), unlock the lock at the bottom, enter your admin password, then check the box to lock the folder. lock the lock and you're done.
    Yes, that is correct. The alternative is to quit all applications prior to logging out. Lion will then have a chance to remove the saved states.
    babowa also wrote:
    And, for the OP:
    It has also been a regular feature of Mac OS to automatically open any window that was open at shutdown. To avoit that behavior, simply close any Finder windows and  properly quit applications by closing their window and using Command + Q (or File >Quit).
    This was true only for the Finder. Prior to Lion, no other apps would launch unless they were included in the Login Items for the account. And the OS would not restore windows for other apps.
    A very small number of apps (TextWrangler is an example) implemented this capability prior to Lion. They could restore previously opened windows. But that is an application feature, and can be controlled by the application's preferences. Lion implements it at the system level, and users have virtually no control on a per application basis.

  • Open sales orders and open deliveries and open billing doc to sap from legesy

    Dear all
    i have some open sales orders and open deliveries and open billing doc are there in the legesy system
    so i want to know how to transfer the doc to sap by using lsmw plz tell me

    Hi Amith,
    it is always good to search in Google before posting .LSMW is very old topic and i am sure you will get lots of Documents on this .Please go through the below link .you will get some idea on this.
    http://scn.sap.com/thread/1012472
    there are 14 steps in LSMW and it is same for all (master data and Transaction Data)
    Pls practice this in your sand box or quality system before working it in the client requirement.
    Hope this helps to you
    Regards
    Sundar

  • Open Purchase Orders and Open Sales Orders

    Hi,
    Please let me know the table names for open purchase orders and sales orders.
    Regards,
    Prii

    HI Priti,
    EKPO-ELIKZ  "Delivery completed" indicator, This tell if the given PO line items has any open quantity or not.
    Logic to find out if a given PO has Open Quantity or not is do the following:
        " select the PO Qunatity.
        SELECT SINGLE MENGE FROM EKPO INTO PO_QTY WHERE
        EBELN = ITAB_PO_LN-EBELN AND
        EBELP = ITAB_PO_LN-EBELP.
        " select the GR qunatity which has been received.
        SELECT SUM( MENGE ) FROM EKBE INTO GR_QTY WHERE
        EBELN = ITAB_PO_LN-EBELN AND
        EBELP = ITAB_PO_LN-EBELP AND
        BWART = '101'.
        " select GR Quantity which has been reversed.
        SELECT SUM( MENGE ) FROM EKBE INTO GR_REV_QTY WHERE
        EBELN = ITAB_PO_LN-EBELN  AND
        EBELP = ITAB_PO_LN-EBELP AND
        BWART = '102'.
        POSTED_QTY =   GR_QTY - GR_REV_QTY .
        OPEN_QTY = PO_QTY - POSTED_QTY.
    Regards,
    -Venkat.

  • I have a macbook pro version 10.7.5 and my mailbox will not open at all and comes up with a quit message even though it is not open. how can i get into my account. it works on my iPhone an i have internet and all other functions working on my computer

    I have a macbook pro version 10.7.5 and my mailbox will not open at all and comes up with a quit message even though it is not open. how can i get into my account. it works on my iPhone and i have internet and all other functions working on my computer

    Launch the Console application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad. Click Utilities, then Console in the icon grid.
    Step 1
    Make sure the title of the Console window is All Messages. If it isn't, select All Messages from the SYSTEM LOG QUERIES menu on the left. If you don't see that menu, select
    View ▹ Show Log List
    from the menu bar.
    Enter the name of the crashed application or process in the Filter text field. Select the messages from the time of the last crash, if any. Copy them to the Clipboard by pressing the key combination command-C. Paste into a reply to this message by pressing command-V.
    When posting a log extract, be selective. In most cases, a few dozen lines are more than enough.
    Please do not indiscriminately dump thousands of lines from the log into this discussion.
    Important: Some private information, such as your name, may appear in the log. Anonymize before posting.
    Step 2
    In the Console window, look under User Diagnostic Reports (not "Diagnostic and Usage Messages") for crash reports related to the crashed process. The report name starts with the name of the process, and ends with ".crash". Select the most recent report and post the entire contents—the text, not a screenshot. I know the report is long. Please post all of it anyway.
    In the interest of privacy, I suggest that, before posting, you edit out the “Anonymous UUID,” a long string of letters, numbers, and dashes in the header of the report, if it’s present (it may not be.)
    Please don’t post other kinds of diagnostic report—they're very long and rarely helpful.

  • When I open up iphoto and click on the events tab then double click on an event, it used to show minis of all the photos in that event.  Now it shows only one photo at a time.  How do I get it back? Can you help?

    When I open up iphoto and click on the events tab then double click on an event, it used to show minis of all the photos in that event.  Now it shows only one photo at a time.  How do I get it back? Can you help?

    On the bottom bar of the window (on the left iPhoto 11, on the right in other versions) note the slider. Drag it left.
    Regards
    TD

  • Saved Tiffs will not open in CS2 and generate a "Could not complete your request because of a program error".

    this was supplied by Ann Shelbourne.
    Saved Tiffs will not open in CS2 and generate a "Could not complete your request because of a program error".
    These files will often open in Photoshop 7.0.1 or in CS1 but not in CS2.
    The trouble may be caused by bad dates in the EXIF data and can originate from an incorrectly-programmed digital camera; or from a scan that was created after after Jan1 of this year (because of a known bug in some scanner software).
    If someone runs into the "Could not complete your request because of a program error" problem, and does not have CS1, try opening the Tiff in TextEdit.
    The EXIF data is right at the top. Check the EXIF data for bad creation dates and change any incorrect ones there.
    Save and close; and then the file will probably open in CS2 without a murmur.

    > If iPhoto causes problems why not open the images from the Finder?
    I get the error if I open a file from within iPhoto using "OPen in external editor" and then alter it (or do not alter it) and try to save it over itself, or save it anywhere else.
    I get the error if I do "Show file" in iPhoto to see the file in the Finder. Then, if I double-click and it opens in PS, and then alter it (or do not alter it) and try to save it over itself, or save it anywhere else.
    > And with »save it anywhere« You indicate that You use the Save As-command?
    Right.

  • I just updated my pages and now it won't load. This is on my iPad. The first version which has the latest version it can have 5.1 or something like that. I am trying to open a document and am worried that if I uninstall and reinstall I will lose all my do

    I just updated my pages and now it won't load. This is on my iPad. The first version which has the latest version it can have 5.1 or something like that. I am trying to open a document and am worried that if I uninstall and reinstall I will lose all my documents

    I just uninstalled it and am waiting for it to reinstall. I sincerely hope that I have not lost everything that I worked on so hard. Now that mobile me is gone, I have not been able to go between devices to transfer things. I was merely trying to take a document I had worked on and open it in pages, but it said my version was too old. When I updated, it wouldn't load. Now I cannot do anything. I hope that the reinstall fixes it without losing everything. Please advise!!! Yes, I am in panic mode.

  • IPhone black screen does not show anything, but I can hear that the device works. I hear the lock open the screen and hear the iPod but the screen remains black

    IPhone black screen does not show anything, but I can hear that the device works. I hear the lock open the screen and hear the iPod but the screen remains black!!

    It's happened to me before as well. Try holding both lock(top right) and home buttons simultaneously until u see a slight flash of wight then just reboot it normally. If that doesn't work try restoring your device from itunes

  • Help with opening Adobe Reader and downloading updates

    I can not open Adobe .pdf files any longer (this started yesterday, prior to that I could open adobe files).
    When I double click a .pdf file I get this notice on my screen: Windows cannot access the specified device path or file. You may not have the appropriate permission to access file.
    So I went to the Adobe download site to download a new copy of Adobe.  When I start the download I get this on the screen:  The instruction at "0x0e3a0068" referenced memory at "0x0e3a0068."  The memory could not be written.  Then two options are listed: click OK to terminate or cancel to debug.  So I click on cancel and I get this on my screen: Internet Explorer has closed this webpage to help protect your computer.   A malfunctioning or malicious addon has caused I.E. to close this webpage.
    I don't have AVG running, I do have avast but I've disabled it.  I ran Registry Mechanic and an I.E. erasure program but nothing helps.
    I have gone into I.E. and reduced the security level to its lowest state but no joy.
    So, any ideas or suggestions on what's the problem and how to overcome it would be appreciated.  Thanks, in advance, for your reply.  Jim R.

    Hi Mike..tried that as well but no joy.  A friend of mine was looking at it all and noticed that it was an I.E. thing as far as not letting me redownload the reader so I went to Mozilla Firefox and I could download a new version but....whenever I attempt to open a .pdf file I get that message, "Windows can not open the specified device, path or file. You man not have the appropriate permissions to access the item." 
    Damn...this is irritating as I need to get to some of thos files as I need them for a Journal I'm working on as editor-in-chief. 
    It all worked just fine last Saturday but starting Monday when I was on my flight out to D.C.  no joy. 
    Sigh...Jim R.
    Jim R.
    Date: Tue, 1 Dec 2009 14:50:27 -0700
    From: [email protected]
    To: [email protected]
    Subject: Help with opening Adobe Reader and downloading updates
    Under the help menu, there is an option to repair the installation of reader. Did you try that?
    >

  • Hi.  I have a Dell PC running Windows 7 64 bit.  I have the latest version of Adobe Reader,  It worked yesterday.  Today I have job training to do that is due tomorrow morning and I can't open PDF files.  I have to open a guide and read it and take a test

    Hi.  I have a Dell PC running Windows 7 64 bit.  I have the latest version of Adobe Reader,  It worked yesterday.  Today I have job training to do that is due tomorrow morning and I can't open PDF files.  I have to open a guide and read it and take a test tomorrow.  I have deleted and reinstalled the application.  I have rebooted.  I have made sure my PDF's are associated with the program.  Every PDF on my computer won't open and I get the same error message.  It simply says Attempt to access invalid address.  How can I fix this?  Thanks.

    Hi Don,
    I have seen this issue fixed for some users by modifying the following registry key:
    The key is "HKLM\System\CurrentControlSet\Control\Session Manager\Memory Management" MoveImages
    Set the key to 1 instead of 0 then reboot the machine.
    In case you still face the issue try the following registry key change:
    The only thing you have to do is rename the following key at the REGEDIT, and everything will be fine !!
    BEFORE:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\iexplore.exe
    AFTER:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\iexplore.old
    Note: Please take a backup of the registry before attempting this change.
    Regards,
    Rave

  • I have recently updated my CC programs to the latest version and now all of my files wont open by default into their respective programs, only if I open the program and go to file open and open the file from there. How can I fix this?

    I have recently updated my CC programs to the latest version (CC2014) and now all of my files wont open by default into their respective programs, only if I open the program and go to file>open and open the file from there. How can I fix this?
    I have tried 'Open with' and the version of the program now installed on my computer isn't even suggested as an option and when I browse for it, the file wont open with it anyway

    On Windows (don't know about Mac), the latest version will always take over the file association, and become the default for indd files. It's impossible to change it.
    But there is a plugin for ID that makes this possible. Never tried it myself.
    https://www.rorohiko.com/wordpress/downloads/lightning-brain-soxy/

Maybe you are looking for

  • CMS System to create a page on the server

    Hi all, I am looking for a way for ColdFusion to create and save an html (or cfml) page generated by a user entering text into a form field on an html template page and submitting the text. I am looking to build an email system to allow the client to

  • How Do I Resolve Constant Kernal Panics?

    I need help troubleshooting what is going on with my iMac.  We've been getting sporatic KPs since about Oct. 22.  We have not been able to use our computer since yesterday, because looking at it the wrong way causes the black screen of death.  I've l

  • How to avoid aggregation on a key figure

    Hi SDN, Is there a way to avoid aggregation on a key figure? We have a situation where we have multiple records for a particular order/item. So a key figure like Net Price simply adds up which is wrong. We just want to repeat it and not aggregate. An

  • Serial numbers in Goods issue

    Hi All, We have an existing Warehouse management process where the Goods issue is first posted. This creates a transfer order. The IDOC created by the transfer order tells the external system to Pick a material. Now we are trying to introduce serial

  • Ipod Touch Sorting Issue

    So I just got my new ipod touch, 32gb 3rd gen and I'm already having problems. When I go into music, albums, I have multiple albums that are exactly the same. They are all listed under the same name, but different artists, but each artist section has