Socket.getInputStream() doesn't initialise empty

I would appreciate any help with the following:
When using a stream socket to transfer a file from a server to a client, I seem to have trouble with the first byte in the socket input steam.
I have isolated the code down to the following:
SERVER CODE
OutputStream os = sock.getOutputStream();
int b = 33; // pick an integer to send
System.out.println("\nFIRST BYTE=" + b); /// here see 33 ok
os.write(b);
os.close();
CLIENT CODE
InputStream is = sock.getInputStream();
int b = is.read(); //<<<< here for some reason b = 10????
System.out.println("\nFIRST BYTE=" + b); /// here display is 10
I do not get this problem with other inputstreams from System.in (ie. keyboard) or file, only get this problem with the socket inputSteam where first byte is always 10 (I think this is a newline char) , then the following bytes are fine. I am going around in circles trying to figure this one out.
Note: a work around is to simply read the first byte and discard but this is not explaining the problem.
Any suggestions?

Thanks for the replies, I have finally nutted out the problem. For those of you interested . . .
The fact that that the byte value was 10 (ie linefeed) gave some hints, finally found a stray �\n� was still in inputstream waiting to be read due to an earlier loop error of mine.
I thought I was instantiating a new inputstream object but in fact was creating and alias for an already created object (containing a left over �\n�).
Problem solved!
I have learnt a lot in the 6hrs of pondering this �simple� problem.
Thanks again

Similar Messages

  • Multiple references to socket.getInputStream()

    I am writing a simple client server game and am trying to pass both input and Objects over the socket stream.
    Is it possible to have:
    BufferedReader ins = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());Or will this cause problems? I am positive of the order of input and objects, so there is no ambiguity on whether to read from ois or ins, but will there be some bad-mojo there anyway?

    Thanks. I've read alot of posts about this and this is the first time I've seen the deprecated readLine solution. Doesn't this seem to be a fairly significant problem? Is BufferedReader supposed to be accepting serialized objects anytime soon?
    I suppose that I could simply close the socket and reestablish a connection using an ObjectInputStream, but what do commercial developers do? Do they just rely on passing String objects or is BufferedReader preferred?

  • Socket.getOutputStream must precede the socket.getInputStream?!? Why?

    This is server code.......
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class DateServer extends Thread {
       private ServerSocket dateServer;
       public static void main(String argv[]) throws Exception {
         new DateServer();
       public DateServer() throws Exception {
         dateServer = new ServerSocket(3000);
         System.out.println("Server listening on port 3000.");
         this.start();
       public void run() {
         while(true) {
           try {
            System.out.println("Waiting for connections.");
            Socket client = dateServer.accept();
            System.out.println("Accepted a connection from: "+
    client.getInetAddress());
            Connect c = new Connect(client);
           } catch(Exception e) {}
    class Connect extends Thread {
       private Socket client = null;
       private ObjectInputStream ois = null;
       private ObjectOutputStream oos = null;
       public Connect() {}
       public Connect(Socket clientSocket) {
         client = clientSocket;
         try {
          ois = new ObjectInputStream(client.getInputStream());
          oos = new ObjectOutputStream(client.getOutputStream());
         } catch(Exception e1) {
             try {
                client.close();
             }catch(Exception e) {
               System.out.println(e.getMessage());
             return;
         this.start();
       public void run() {
          try {
             oos.writeObject(new Date());
             oos.flush();
             // close streams and connections
             ois.close();
             oos.close();
             client.close();
          } catch(Exception e) {}
    }This is client code....
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class DateClient {
       public static void main(String argv[]) {
          ObjectOutputStream oos = null;
          ObjectInputStream ois = null;
          Socket socket = null;
          Date date = null;
          try {
            // open a socket connection
            socket = new Socket("127.0.0.1", 3000);
            // open I/O streams for objects
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
              System.out.println( "BAU!" );
            // read an object from the server
            date = (Date) ois.readObject();
            System.out.print("The date is: " + date);
            oos.close();
            ois.close();
          } catch(Exception e) {
            System.out.println(e.getMessage());
    }OK.
    Those work just fine. Now if you put socket.getInputStream before the socket.getOutputStream then it hangs!
    Any ideea why this happens and why is not documented... I just lost tow hour tring to figure it out why my program just hangs. After I have set the order as In the example above all works....
    If anyone knows why please share your knowledge...
    Hope this will save others a lot of lost time.

    The order matters because the ObjectOutputStream constructor writes a stream header and the ObjectInputStream constructor reads the header.
    If both ends of the conversation do "new ObjectInputStream()" they both forever wait for the other end to write the header. So one end needs to create the output stream first and the input stream second, and the other end in the other order (or do them in different threads.)
    If it isn't documented it should be IMHO. Re-check the javadocs; if it isn't mentioned file a bug report to Sun. There is a bug parade link on http://java.sun.com/ somewhere.

  • K8N NEO 2 Platinum sometimes doesn't initialise the keyboard and mouse

    I got a K8N NEO 2 Platinum for christmas, and everytime it reboots (fine when you turn it on fresh), it produces the shortest of bleeps, and doesn't initialise the keyboard and mouse. The only way to do anything then is to go for the power button and windows xp shuts down. It is still responding, just the bios hasn't initialised the keyboard and mouse.
    Anyone know anything about this, and how to solve it?

    ok, thanks
    Athlon XP 3500+ Newcastle
    MSI K8N NEO2 Platinum (BIOS v 1.4)
    Keytronic PS2 keyboard (KT800PS2UK12)
    A4 Tech 4D PS2 mouse (IRW-25)
    geforce 4 ti 4600
    SB Live Platinum
    wintv go
    DVD ROM (OEM unbranded)
    DVD +/- RW LITEON
    80GB SATA HDD
    40GB IDE HDD
    2x 256MB DDR 333MHz RAM (PC2700)
    everything worked fine till the new mobo, and still works fine xcept this problem
    thanks again

  • FtpAdapter doesn't transfer empty files

    Hi there,
    I am trying put an empty file (= 0 bytes) to another server via the FtpAdapter, using a SFTP-Connection.
    The log doesn't display any error but only the successful transmission, but on the
    destination server there is no file written. I've tried to switch from ascii to binary without success. Here's the log:
    <File Adapter::Outbound> Successful in setting up the SFTP connection
    <File Adapter::Outbound> Managed Connection Created
    <File Adapter::Outbound> Adding Event Listener
    <File Adapter::Outbound> Creating Connection
    <File Adapter::Outbound> Connection Created
    <File Adapter::Outbound> Connection manager allocated connection :oracle.tip.adapter.ftp.FTPConnection@ae401b
    <File Adapter::Outbound> Creating FTPInteraction
    <File Adapter::Outbound> Creating an SFTPSender
    <File Adapter::Outbound> SFTP Sender created
    <File Adapter::Outbound> FTPInteraction Created
    <AdapterFramework::Outbound> Instantiating outbound JCA interactionSpec oracle.tip.adapter.ftp.outbound.FTPInteractionSpec
    <AdapterFramework::Outbound> Populating outbound JCA interactionSpec oracle.tip.adapter.ftp.outbound.FTPInteractionSpec with properties: {FileNamingConvention=dummy, OpaqueSchema=true, NumberMessages=1, PhysicalDirectory=/, FileType=binary}
    <AdapterFramework::Outbound> file:/u01/app/oracle10g/product/10.1.3.1/OracleAS_1/bpel/domains/default/tmp/.bpel_CpOutput_1.0_0053ad28af82f0120114b2f22390139c.tmp/FtpSendDiva.wsdl [ Put_ptt::Put(opaque) ] - Starting JCA LocalTransaction
    <AdapterFramework::Outbound> file:/u01/app/oracle10g/product/10.1.3.1/OracleAS_1/bpel/domains/default/tmp/.bpel_CpOutput_1.0_0053ad28af82f0120114b2f22390139c.tmp/FtpSendDiva.wsdl [ Put_ptt::Put(opaque) ] - Invoking JCA outbound Interaction
    <File Adapter::Outbound> FTP outbound adapter interaction invoked : oracle.tip.adapter.ftp.outbound.FTPInteractionSpec@18bdbcf
    <File Adapter::Outbound> FTP outbound adapter write file interaction invoked.
    <File Adapter::Outbound> File Adapter received an input Record
    <File Adapter::Outbound> Waiting outside sync object.....
    <File Adapter::Outbound> Considering header for filename, output filename from header: testfile.csv
    <File Adapter::Outbound> Not Considering header for directory as it is blank
    <File Adapter::Outbound> Inside getUniqueDirectory::InteractionSpec getProcessName for [bpel://localhost/default/CpOutput~1.0/] returned [CpOutput~1.0]
    <File Adapter::Outbound> GenUtil::getUniqueDirectory::InteractioSpec [localhost_default_CpOutput~1.0_/FtpSendD//] ==> [CpOutput~1.0/CKlx14IRspFHDdTf6wtdDA==]
    <File Adapter::Outbound> MD5 BaseDir is [cut]
    <File Adapter::Outbound> Batcher created using staging : true with number of messages : 1
    <File Adapter::Outbound> ServerType: unix
    <File Adapter::Outbound> Specified ServerType: unix, using unix LineSeparator
    <File Adapter::Outbound> Input Record: javax.xml.transform.dom.DOMSource@10c1cdc
    <File Adapter::Outbound> Translating....
    <File Adapter::Outbound> Outbound Translation done.
    <File Adapter::Outbound> Refreshed (staging/num Messages) file count : 1
    <File Adapter::Outbound> Wrote to Control File
    <File Adapter::Outbound> Batching staging File: staging0
    <File Adapter::Outbound> Batcher sending to sender for output file writing
    <File Adapter::Outbound> Sending File to output Dir
    <File Adapter::Outbound> Obtaining SFTP Agent
    <File Adapter::Outbound> Putting file: testfile.csv to: / Append: false
    <File Adapter::Outbound> Put file:
    <File Adapter::Outbound> Done Writing to output file testfile.csv in dir / !!
    <File Adapter::Outbound> End clearing Control File
    <File Adapter::Outbound> Deleting staging File: staging0
    <File Adapter::Outbound> End clearing Control File
    <File Adapter::Outbound> Interaction gets a ok response
    <File Adapter::Outbound> Done with Input Record
    <AdapterFramework::Outbound> file:/u01/app/oracle10g/product/10.1.3.1/OracleAS_1/bpel/domains/default/tmp/.bpel_CpOutput_1.0_0053ad28af82f0120114b2f22390139c.tmp/FtpSendDiva.wsdl [ Put_ptt::Put(opaque) ] - Committing JCA LocalTransaction
    It works when the file is not empty.
    It also works, when i transfer the file manually via 'sftp', so the problem is not the sftp-Server.
    Any hints how I can transfer empty files?
    We're using 10.1.3.1.
    TIA, Roman

    Do you have the right boxes checked to sync them to your iPod:
    iTunes 11 for Windows: Set up syncing for iPod, iPhone, or iPad
    iTunes 11 for Mac: Set up syncing for iPod, iPhone, or iPad
    Did you look in the More section of the Music app?
    Have you tried using the Spotlight search> Maybe you just can't find them

  • Why doesn't Mail empty Junk folders at every quit?

    I select "empty Junk at quit" but still Mail doesn't empty those folders at every quit. Anyone know why this happens?

    This is still happening to me with Mail v6.0 (1485) after updating to Mountain Lion.  I have to quit and restart Mail after resuming from sleep to get it to connect to any of my accounts.  One iCloud and one GMail account.
    I have tried starting from scratch by removing all accounts, files in my Library ("Application Support" and "Caches" folders) and cleaned up my keychain, but still the problem persists.

  • Socket.getInputStream hangs

    I have a simple client/server app, and the client hangs when I try to get the input stream coming out of the server. I have the following code on the server:
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    port = 49152;
    server = new ServerSocket(port, 0, InetAddress.getLocalHost());
    sock = server.accept();
    oos = new ObjectOutputStream(sock.getOutputStream());
    ois = new ObjectInputStream(sock.getInputStream());
    String inMsg = (String) ois.readObject();
    oos.writeObject(outMsg);
    oos.close();
    ois.close();
    sock.close();And I try to invoke it with this code on the client:
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    String inMsg = "";
    int port = 49152;
    try {
         Socket sock = new Socket(InetAddress.getLocalHost(), port);
         oos = new ObjectOutputStream(sock.getOutputStream());
         ois = new ObjectInputStream(sock.getInputStream());//the code hangs here
         oos.writeObject(outMsg);
         inMsg = (String) ois.readObject();
            oos.close();
         ois.close();
         sock.close();
    } catch (Exception e) {
         return "";
    return inMsg;
         The code hangs where indicated in the comments. Can someone tell me what I'm doing wrong?
    Edited by: MidnightJava on Apr 10, 2008 4:55 AM

    Can you please explain the rationale for your suggestion? What sort of problem is it addressingThe constructor for ObjectOutputStream writes a header to the stream. The constructor for ObjectInputStream reads it. Try constructing them in the opposite order at both ends and you will see a lovely deadlock. The flush() is required if there is a BufferedOutputStream under the ObjectOutputStream.
    is it a good idea to do it always when creating streams from a socket?It's essential when dealing with object streams. Other streams, no.

  • Is Socket.getInputStream() expensive?

    Hi,
    I am writing an app. that will communicate frequently with other instances of itself on other machines. Now, in the beginning I am going to create socket connections among all apps on all machines. I was thinking of storing the resulting socket variable in a HashMap keyed by machine name. But, then everytime I have to write a message to another machine I would have to do this:
    Socket sock = machine2socket.get(machineName);
    ObjectOutputStream oos= new ObjectOutputStream(sock.getInputStream());
    oos.writeObject(...);I am wondering if it would be more efficient to create the ObjectOutputStream once during initialization and then retrieve that from a HashMap as well.
    Any thoughts?

    No, it comes free with Java... :-)
    First, presumably, the better way would be to create an object to hold the socket, and when you create that object, you pass it the socket to the constructor and in that create your input and output stream wrappers (Object stream, BufferedReaders, whatever), so you aren't creating new ones all the time.
    That being said, if you are talking about relatively few clients, I suppose this architecture could be okay. But the more clients running and talking to each other, the more cross connections you have. If you are going to broadcast the same objects to all clients, it might be better to have 1 server that all clients connect to. Then you send objects to the server and let it resend to all other clients. You can have some kinda protocol to send objects to specific clients, get a client list, notification of client connect/disconnect, various other things. This way you have 1 socket connection per client to 1 server, instead of X connections to each of X clients.
    Further, the clients have to know where all the other clients are or find them somehow (port scan, for example). A common server is going to be easier to configure then configuring or auto-discovering other clients.

  • Socket.close doesn't work in Windows browsers?

    I've been trying to figure this out for days and I can't seem to find anything on why this is happening or how to fix it.
    I have an FTP program written that uploads ByteArrays through sockets.  It works great on my Mac!  I open a command connection, then a data connection, send the ByteArray and then use socket.close() on my data connection.  This causes the server to disconnect me and sends the 226:transfer succeeded message back through my command connection.
    The problem is that in IE8, FF 3.5, and Safari 4 on Windows the socket.close() func does not make the server close the connection.  The fact that it works in all of my Mac browsers, and the IDE, but not in Windows browsers makes me think that it's something to do with the Flash Player.  Is this possible?
    My FP version check data:
    MAC 10,0,32,18
    WIN 10,0,32,18
    Does anyone know how I can fix, or even debug, this?

    does anyone have any idea what could be going on here?  am i completely out to lunch?

  • QT 7.1.3 plugin doesn't initialise properly in IE7

    Since installing IE7, I have had problems with the Quicktime 7.1.3 plug-in for Internet Explorer. The issue seems to be related to the IE7 security "enhancements" but I have not been able to find a solution.
    An example - if I click on a movie trailer on the QT Movies web site, I get a "Plugin Error" message that reads "An error occurred inside a plugin contained on this page". If I OK it away I get a second "Plugin Error" message that reads "The plugin did not initialize properly". If I persist in trying, IE7 will crash. This is in the "Internet" security zone for IE7.
    Some probably related behaviour that I have observed: If I try to open a .mov file on a network drive with IE7 (this is in the "Local Intranet" security zone), I get a blank browser window. No error message, but nothing happens. If I open the same file on a local drive (in the "My Computer" security zone), the QT plugin and IE7 do their job properly. The weird thing here is that, once I have intialised the plugin properly in this way, I can navigate to the QT Movies web site using the same browser window and eveything works perfectly.
    Is there some security setting in IE7 that I have missed? Any ideas on how to solve this problem so that the QT plugin initialises properly in the "Internet" security zone of IE7?

    Yeah, this has been going on since early Nov'06, w/no response from Apple.
    Read here:
    http://discussions.apple.com/thread.jspa?threadID=725520
    I don't know if Apple has abandoned their software plugin for IE or what. I'd just recommend to move on to other audio video formats that do work, as a solution does seem likely to be forthcoming from Apple.

  • AS3.0 socket script doesn't work with flex coldfusion local server

    I am having a real problem using my script in flex coldfusion
    project. I tried everything I can to get an answer including
    posting a question in two groups with no success.
    I created a class that goes and connect through a socket
    connection and it works fine under “basic” flex
    project, however when I try to use the package in a flex coldfusion
    project I keep getting error messages:
    *** Security Sandbox Violation ***
    Connection to domainName.com:60 halted - not permitted from
    http://localhost:8500/ProjectName/bin/fileName.swf
    Error #2044: Unhandled SecurityErrorEvent:. text=Error #2048:
    Security sandbox violation:
    http://localhost:8500/ProjectName/bin/fileName.swf
    cannot load data from domainName.com:60. At
    com.elad.as3.socket::socketConnect$iinit()[C:\CFusionMX7\wwwroot\ProjectName\com\elad\as3 \socket\socketConnect.as:14]
    It looks to me that because there are two URL
    http://localhost:8500/ProjectName/bin/fileName.
    and
    C:\CFusionMX7\wwwroot\ProjectName\com\elad\as3\socket\socketConnect.as
    The player set the security in full effect and I cannot
    access other servers. I tried everything including setting the
    security and adding my local server to the approved servers.
    This is a real problem because I will not be able to test my
    application locally.
    Thanks in advance for the help,

    does anyone have any idea what could be going on here?  am i completely out to lunch?

  • My iPad socket jack doesn't have Apple logo

    I have had both iPhone and iPad but unfortunately I noticed that both connecting jack are different because one jack have had Apple logo and my iPad jack doesn't have logo ,How could i trust made by Apple?

    Not all Apple headphones have the Apple logo on the jack.

  • Trash is empty but it doesn't look empty???

    Usually if trash has something in it then the image of the trash can has some screwed up paper in it and when it is empty there is no paper but for some reason mine won't have an empty trash can image after I deleted all the trash.

    It was the same when I had a new dock so I switched it back but I found out that there is a file in there only visible in list view for some reason; I tried getting its info when I found it and I believe it is the trash inside the trash because its picture was the trash picture but I have not been able to get info it since. I can not empty it out of trash but if I drag it to out of the window, which it gives a white block sign telling me it can't, it disappears out of trash until I put something in trash. Because I know the trash is in my Home folder I tried dragging it there but it does the same block.
    please help this is starting to sound more serious

  • PackageMaker doesn't include empty folders

    I am trying to create a package that contains empty folders. Items may be installed into these folders from another program. All items are listed when I authenticate to archive the Package_contents on building. Most of the empty folders are not in the final package.
    My example Package_contents contains where all icm and firmware directories are empty:
    /usr/local/share/foo2/
    /usr/local/share/foo2/icm/
    /usr/local/share/foo3/
    /usr/local/share/foo3/crd/
    /usr/local/share/foo3/crd/file1
    /usr/local/share/foo3/crd/file2
    /usr/local/share/foo3/icm/
    /usr/local/share/foo4/
    /usr/local/share/foo4/firmware/
    /usr/local/share/foo4/icm/
    The package as built by PackageMaker v2.1.1(123) in OS X 10.4.9 contains:
    /usr/local/share/foo2/
    /usr/local/share/foo2/icm/
    /usr/local/share/foo3/
    /usr/local/share/foo3/crd/
    /usr/local/share/foo3/crd/file1
    /usr/local/share/foo3/crd/file2
    /usr/local/share/foo4/
    Is there some way to get all the empty directories included in the build?
    Matt
    Mac Mini G4; B&W G3/300    

    I tried putting some dummy files in the empty
    folders. They got included in the package as I
    would
    have expected. I think this is a bit messy.
    True. It is a bit messy but you can always include
    some code in your application which deletes the dummy
    files the first time it runs... or perhaps build the
    delete into the post flight script.
    It would probably be less messy and less confusing to create the package with the dummy or placeholder files and delete them in the postflight. It would seem to make more sense and "be more honest" to list "placeholder" files of zero bits in the Archive.bom than to create extra directories in the postflight.
    As I mentioned in my previous response, PackageMaker 1.2 running in OS X 10.3.9 builds the package as I want, so I won't have to deal with the issue.
    Matt

  • Trash doesn't look empty after delete - looks like there is trash

    New to Leopard, empty trash (nothing in folder) but icon still looks full.
    Any ideas?
    Thanks

    FWIW, in list view the file shows up (for a second, it says alias) then deletes and the trash is empty.
    It then reappears in a few minutes which leads me to believe its some sort of system process.
    _*Here is link to image*_
    http://img239.imageshack.us/my.php?image=trashrd5.png
    Wondering if something like mainmenu or oynx can fix this.
    I also have a TIGER BACKUP IMAGE and a LEOPARD INSTALL IMAGE on an external HD and wondering if I can use CCopy to erase my MBP HD and just use that although I would want to change the root user name. Its things like LOGIC being better in Leopard that I like but things like this (BUGS) that make me leary...
    Its too bad I can't access the TIME MACHINE as on the LEOPARD INSTALL bootup (external) I ran time machine for a few days and it backed up the whole computer. Although, I want to get rid of this bug more so seeing how I just bought an iPod (my first) and synched it up. Actually, it was after this process and deleting some songs NOT authorized for this MAC that this problem started to come up.
    Help appreciated.
    Take a look at the image and let me know what you think.

Maybe you are looking for

  • How to start realracing 3 in iphone4s iOS 7

    I had realracing 3 but there is no  start option in the game, please  say how to start the game

  • CSS menu in IE 7

    I have a CSS styled menu on website that worked perfectly fine in IE 6, but doesn't work at all in IE 7. heres the code: any suggestions?

  • Acrobat Reader cannot open e-mail program

    Hello, I´ve a little problem with the Acrobat reader. After installing on our new computer (Windows 7) the reader cannot find our e-mail program (Windows Live Mail). Can anyone say me where the problem is? Regards Chris

  • Search server side?

    Hi guys I have a big fat iphoto library on my main mac which I like to look at on the ibook. But search is dimmed. I tell you looking through 6000 photos on wireless takes a looooooong time and with no search I usually just give up and goto the other

  • Transferring My Catalog To Daughter's Computer

    Both my daughters and I use PSE9.  I have a large family ancestry catalog that I want to pass on to them.  They both have their own PSE catalogs with their family pictures.  So I want to give them my ancestry catalog which would create a 2nd catalog