Trying to understand Java Sockets

First, I have been able to find enough examples to get off ground zero and now I need a little help understanding what I have found.
Secondly, I have a problem that i need a little help on.
First - as I understand it the // indicates a comment and then I found a snippet that helped me get what I wanted but I can't understand this
     } catch(IOException e) {
     e.printStackTrace();
     // System.exit(3);
return;
in this is example is the //System.exit(3) doing anything or is it just intended as a comment? What does the return do? Where does it return to?
Secondly - the problem. In setting up the socket, I am trying to trap for a few common errors such as parameter not entered on the command line, invalid host, invalid port, or port not listening, etc. Some of these I have been able to figure out because people have examples that help me figure out how to use it but others don't. Here is my code snippet so far. I am trying to explore the PortUnreachableEception class and haven't had any success at all. Where would it go and what would be the right way to use it in this scenario?
Thanks
George Mizzell
import java.io.*;
import java.net.*;
public class GetBoth3{
public static final int GetDayTimePort = 13;
public static final int GetQuotePort = 17;
public static void main(String[] args){
     if (args.length != 1) {
     System.err.println("Oops, no address to find");
     // System.exit(1);
     return;
     InetAddress address = null;
     try {
     address = InetAddress.getByName(args[0]);
     } catch(UnknownHostException e) {
     e.printStackTrace();
     // System.exit(2);
return;
     Socket getDateTime = null;
     try {
     getDateTime = new Socket(address, GetDayTimePort);
     } catch(IOException e) {
     e.printStackTrace();
     // System.exit(3);
return;
     InputStream in = null;
     try {
     in = getDateTime.getInputStream();
     } catch(IOException e) {
     e.printStackTrace();
     // System.exit(5);
return;
     BufferedReader reader = new BufferedReader(new InputStreamReader(in));
     String line = null;
     try {
     line = reader.readLine();
     } catch(IOException e) {
     e.printStackTrace();
     // System.exit(6);
return;
     System.out.println("The current date and time on " + address + " is " + line);
     // System.exit(0);
return;
} // GetBoth3

Starting with your first question:
} catch(IOException e) {
e.printStackTrace();
// System.exit(3);
return;
System.exit(3) is commented out there, it is not doing anything. At first it seems confusing because... why write a line of code, then comment it out? Does it tell us anything? What's going on? The reason that it's commented out is either because the original programmer put System.exit(3) there and decided to use return instead, but didn't want to forget what the original line of code was, or, he wanted to suggest to the reader that perhaps System.exit(3) may be more appropriate than return. Sometimes, when I am debugging an application I wrote, I comment out lines of code without deleting them, so that I won't forget what they were. Or, I comment out my debugging code so that I can easily use it again later without it being compiled into release versions.
So, to answer your question. The //System.exit(3) does nothing, it is just intended as a comment. Return causes the flow of execution to jump out of the method that it is currently in and return to the calling method. For example:
    public static void main (String[] args) {
        System.out.println("Calling poo(true):");
        poo(true);
        System.out.println("Calling poo(false):");
        poo(false);
        System.out.println("Sorry, no more poo.");
    public static void poo (boolean do_return) {
        System.out.println("First line.");
        if (do_return) return;
        System.out.println("Second line.");
    };The output should be:
    Calling poo(true):
    First line.
    Calling poo(false):
    First line.
    Second line.
    Sorry, no more poo.I don't know if any of that works, I just typed it here. But, you should be able to see what I'm getting at. If do_return is true in poo, then the return statement causes poo to RETURN to main (which is the function that poo was called from) before printing "Second line.".
By contrast, if I would have put System.exit(3) in poo() instead of return, then after calling poo(true) and printing "First line.", the program would have exited back to the system, and "Calling poo(false):" would never have been printed.
So, in the code that you typed, in GetBoth3.main:
if (args.length != 1) {
System.err.println("Oops, no address to find");
// System.exit(1);
return;
Putting a commented out //System.exit(1) does nothing in your program, it's just a comment. When ever you use "return" from main, since nothing called main, returning from main just exits the program and returns to the system.
So:
1) Use return in a method to stop executing the rest of the code in the method, and exit the method.
2) Use return in main() to end the program. This is the same as typing System.exit(0) in main.
3) Use System.exit(code) anywhere in your program to end the program at any given time.
Note that the following code:
    public myMethod () {
        // Do some things...
        if (some_expression == true) return;
        // Do some more things....
    };is functionally equivalent to:
    public myMethod () {
        // Do some things...
        if (some_expression != true) {
            // Do some more things...
    };But the first one is a bit easier to read, esp. when your code gets more complex.
Here is my code snippet so far. I am trying to explore the
PortUnreachableEception class and haven't had any success at all.
Where would it go and what would be the right way to use it in this
scenario?
If you look at the class derivation tree at the top of the javadoc page for PortUnreachableException, you see that one of the classes it is derived from is IOException. Whenever you use a try...catch block, not only does "catch" catch whatever type of exception you specify, but it also catches all exception classes DERIVED from the one that you specified. So, by catching an IOException, you are, in fact, also catching PortUnreachableExceptions. The problem is, in this code...
    try {
        getDateTime = new Socket(address, GetDayTimePort);
    } catch (IOException iox) {
        System.out.println("Error: " + iox);
        System.exit(0);
    };...although you are catching an IOException (and PortUnreachableException's) as well, you have no clean way of differentiating between PortUnreachableException and any other IOException in your code (except by using instanceof, which I can explain later if you want, but it's not really the preferred way to do it in this case).
You could try the following exception handler instead:
    try {
        getDateTime = new Socket(address, GetDayTimePort);
    } catch (PortUnreachableException px) {
        // Stuff
    };But then you will get an uncaught exception compiler error, because the Socket constructor throws an IOException, and you are only catching a subset of exceptions derived from IOException, so any other exceptions besides PortUnreachableException (and the exceptions derived from PortUnreachableException) will remain uncaught by your exception handler.
The solution is to catch both, like so:
    try {
        getDateTime = new Socket(address, GetDayTimePort);
    } catch (PortUnreachableException px) {
        System.out.println("Invalid port specified!");
        System.exit(some_exit_code);
    } catch (IOException iox) {
        System.out.println("Error creating socket: " + iox);
        System.exit(some_exit_code);
    };Note that the order in which your catch statements appear is important. If an exception is thrown in the try block, the program will go to each catch block in order, and execute the first one that applies. So, since PortUnreachableException is derived from IOException, and can therefore be caught by IOException catch blocks, the following code will not do what you want:
    try {
        getDateTime = new Socket(address, GetDayTimePort);
    } catch (IOException iox) {
        System.out.println("Error creating socket: " + iox);
        System.exit(some_exit_code);
    } catch (PortUnreachableException px) {
        System.out.println("Invalid port specified!");
        System.exit(some_exit_code);
    };Since the IOException catch block appears first, and since PortUnreachableExceptions can be caught be IOException catch blocks, then the IOException catch block code will execute, not the PortUnreachableException catch block code.
Also, you may be confused about a few other things I threw in my code:
First of all, "some_exit_code" is whatever exit code you want. The exit code you use does not directly affect your application in any way. Exit codes are useful if you say, spawn your application from another process, and then you want the spawning process to be able to know some information about how your application exited. I can explain that better too, if you want.
Secondly, I used System.exit() instead of return in the main() exception handlers just so that I could control the exit code of the application. If you have no use for exit codes, just use return from main. Also, keep in mind, if you use System.exit() in ANOTHER method (not main) instead of return, then you will exit the program rather than returning from the method.
Also, System.out.println("Error: " + iox) will print a good amount of detail about the IOException iox. Although it won't be as useful as printStackTrace() to you, the developer, it will be more readable than printStackTrace() to the common user.
As an aside, relating to System.out.println, if you define the following method in one of your classes:
    public String toString () {
        return "A string representation of this class.";
    };Then you can use System.out.println(MyClass), or String i = "Description: " + MyClass to print readable information about MyClass. I didn't explain that well so here is an example:
    // OddEven.java
    public class OddEven {
        protected int i;
        public OddEven (int i) {
            this.i = i;
        public String toString () {
            if ((i % 2) == 0) return "even number";
            else return "odd number";
    // Whatever.java
    public class Whatever {
        public static void main (String[] args) {
            OddEven o = new OddEven(31);
            OddEven e = new OddEven(100);
            System.out.println("OddEven o: " + o);
            System.out.println("OddEven e: " + e);
    };That should work, haven't tested it though. But basically, any time an Object gets converted to a String (for example, by passing an Object to a function expecting a String, or by use '+' to concatenate an Object to a String), the toString() method of that Object is called, and the return value is used as the String.
That example should give you another idea about what return does, too.
If you want me to explain instanceof, exit codes, or class derivation and inheritance, lemme know.
Hope any of this helps.
Jason Cipriani
[email protected]
[email protected]

Similar Messages

  • Trying to understand java

    Trying to understand corba
    please tell me what the inout in this coode means:
    boolean book_search(inout b_item book, inout client olvas) raises (BookNoAvail)
    The type of parameter passing in Java is that it makes a copy of the parameter and themn in method somthing happens??
    So which one is it out of the two: pass by reference and pass by value?

    please tell me what the inout in this coode means:A parameter that supplies input as well as accepts output is an INOUT parameter.

  • Trying to understand Java servers

    I have been trying to get an understanding of Java ServerSockets and have hit a dead-end here.
    This is just the first part of the server code and I can't see what the compiler does not like about this. The compiler dies and puts the arrow on the "a" of the word accept. I have looked at lots of different examples of server codes and no 2 resources have the same way of doing it.
    Does anyone have any idea first of all what is wrong with mine below and
    what it should be?
    thanks
    George Mizzell
    import java.net.*;
    import java.io.*;
    public class STServer {
    public static void main (String[] args) throws IOException {
    if (args.length != 1) {
    System.err.println("Oops, invalid parameters");
    return;
    Socket client = accept (Integer.parseInt (args[0]));
    try {

    I apologize for not including the rest of the code. As a newbie, I was thinking that the code processed sequentially and the lines after the problem did not play a role in causing the compile error. Here is the complete listing.
    Thanks for reading it and pointing this out
    import java.net.*;
    import java.io.*;
    public class STServer {
    public static void main (String[] args) throws IOException {
    //test for correct number of parameters - ie must enter a port number
    if (args.length != 1) {
         System.err.println("Oops, invalid parameters");
         return;
         Socket client = accept (Integer.parseInt (args[0]));
         try {
              InputStream in = client.getInputStream ();
              OutputStream out = client.getOutputStream ();
              out.write("Welcome to the Echo Server.\r\n".getBytes("latin1"));
              PrintWriter p;
              PrintWriter ToClient = new PrintWriter(client.getOutputStream());
              String UserName = System.getProperty("user.name");
              String sendtext;
              sendtext = "You are now connected to " + UserName + ".\r\n";
              out.write ("You are now connected to the Echo Server.\r\n"
         .getBytes ("latin1"));
              out.write (sendtext.getBytes ("latin1"));     
              int x;
              while ((x = in.read ()) > -1)
         out.write (x);
              } finally {
                   System.out.println ("Closing");
                   client.close ();          
              System.out.println ("Starting on port " + args[0]);
              System.out.println ("Waiting");
              System.out.println ("Accepted from " + client.getInetAddress ());
              EchoServer5.close ();
         } catch (IOException e) {
              System.out.println("Port did not accept connection:" +
                   Integer.parseInt (args[0]));
         System.exit(-1);
    }

  • Trying to understand OIM - Please help

    Hello All,
    I am pretty new to OIM, just trying to understand how OIM works. For the past 4 years I was in Sun IdM and planning to switch over to OIM.
    I read some documentation, I think OIM will perform basic provisioning and it contains out of box connectors to do basic provisoning. I have some questions can anybody please help
    - Sun IdM uses Express language to develop custom workflows or forms, in OIM to develop workflows which language did you use, is it Java or any other language?
    - If I want to provision users on AS/400, HP Open VMS or AIX systems, how can I do that I don't see any out of box connectors for these resources, so in order to integrate these resources do we need to write our own custom connectors?
    - If the out of box connector does not support a specific function on a resource what are the options do we have? for example if the AD connector does not support to delete the exchange mailbox, how your going to perform this in OIM? Do we need to write a Java code for this?
    - How much Java coding is necessary in OIM?
    - Is OIM supports role based provisioning?
    Please share any information.
    Thanks in advance.

    Sun IdM uses Express language to develop custom workflows or forms, in OIM to develop workflows which language did you use, is it Java or any other language?
    - JAVA
    If I want to provision users on AS/400, HP Open VMS or AIX systems, how can I do that I don't see any out of box connectors for these resources, so in order to integrate these resources do we need to write our own custom connectors?
    - If OOTB connectors are not available then you'll have build you own connector as per Target Resource.
    If the out of box connector does not support a specific function on a resource what are the options do we have?
    - You'll have customize their connector as per your requirements or write your own
    How much Java coding is necessary in OIM?
    - We can't calculate how much java. It's totally depends on requirements how much code you'll ahve to write. But everything will be done using Java only.
    - Is OIM supports role based provisioning?
    Here Group represent Role. At a small scale it supports. But for large scale you'll have to use Oracle Role Manager as you do in Sun Role Manager.

  • Application hangs while trying to create a socket

    Hello,
    We have a third party application that makes HTTP connections using a old version of HTTPClient. Recently we have run into problems where the application hangs as one thread seems to hang while trying to create a socket (thread dumps show the hang occurs in native code) and other threads end up waiting for this thread as they need to obtain a lock on HTTPClient.HTTPConnection. We found out that HTTPClient was not setting a timeout on the underlying socket (SO_TIMEOUT) and the relevant patch has been implemented in the hope that if the condition arises again the offending thread will be timed out and allow other threads to try and continue.
    We will not be able to see if the patch works until Monday and I would like to understand the problem a little better if it fails. My question at what point will the socket timeout starting ticking? As our offending thread is waiting in native code is there a chance that the timeout will not be "active".
    Also can anyone provide reasons for an application hanging while trying to create a socket and any suggestions for monitoring or mitigating this problem?
    Thanks a lot.
    Sun Solaris 5.8
    JDK 1.4.1 b02

    It looks like our version of the JDK offer a connect method with a timeout value, I think this will do the trick.

  • Trying to understand the code???

    Hi,
    I am trying to understand the following bit of code, currently the code puts each catalogue into a different row of the table but i want each catalogue to be put in the next column
    (so the catalogues appear across the page on the actual web page). The following code is for the page in question but im not sure how much is relevant so i will paste it all and highlight the section i think is relevant:
    <html>
    <%-- DECLARATIONS --%>
    <%@ page import="se.ibs.ns.cf.*,  se.ibs.ccf.*, se.ibs.bap.*, se.ibs.bap.util.*, se.ibs.bap.web.*,  java.util.*, se.ibs.ns.icat.*, se.ibs.bap.asw.cf.*, java.lang.*" %>
    <% ItemCatalogueBean bean = (ItemCatalogueBean)SessionHelper.getSessionObject("ItemCatalogueBean",session);
       String resourcePath = bean.getResourcePath(null);
       String title = "Product catalogue";
       String languageCode = bean.getLanguageCode();
    %>
    <%@ include file="FuncHead.jsp" %>
    <BODY class="IBSBody" onLoad="loaded = true;">
    <form method="POST" action=<%= bean.getEncodedServlet("se.ibs.ns.icat.ItemCatalogueSearchServlet", response) %> name="basicForm">
    <%@ include file="FuncSubmitScript.jsp" %>
    <%@ include file="FuncPageBegin.jsp" %>
    <div align="center">
      <table border="0" width="895">
        <tr>
          <td align="left" width="502">
    <div align="left">
      <table border="0" width="500">
        <tr>
          <td class="IBSPageTitleText" align="left" valign="top" width="238">
              <%@ include file="FuncPageTitle.jsp" %>
              <%@ include file="FuncPageTitleImage.jsp" %>
                    <br>
           On this page you can see the product catalogues. Click on one of the
           links to go to the next level. Alternatively you can click the <b>Search
           catalogue</b> button to find the products of interest.</td>
               <td width="248" valign="bottom">
                <div align="left"><%@ include file="FuncShoppingCart.jsp" %></div>
               </td>
        </tr>
      </table>
    </div></td></tr></table></div>
    <input type="submit" value="Search catalogue" name="ACTION_NONE" onClick="submitButtonOnce(this); return false">
    <hr>
    <%-- REPEAT CATALOGUES --%>
    <div align="left">
    <table border="0" width="100%">
    <% Vector catalogues = bean.getItemCatalogues();
            int cataloguesSize = catalogues.size();
               for (int i = 0; i < cataloguesSize; i++){
                      BAPItemCatalogue cat =  (BAPItemCatalogue) catalogues.elementAt(i); %>
              <%-- LINK AND MARK AS NEW --%>
                  <tr>
                         <td width="23%"><a class="IBSMenuLink" href="link" onClick="javascript:invokeLink('<%= bean.getEncodedServlet("se.ibs.ns.icat.ItemCatalogueCategoryServlet", response) %>?CODE=<%= ToolBox.encodeURLParameter(cat.getCode())%>'); return false">
                              <%= cat.getDescription(languageCode) %></a>
                         </td>
                         <td width="40%" align="right">
                              <% if (cat.isNew()) {%>
                                     <img border=0 src="<%= resourcePath %>new.gif">
                              <% } %>
                        </td>
                  </tr>
              <%--  CATALOGUES IMAGE AND INTERNET INFORMATION (text, multimedia objects,downloads, links...) --%>
                  <tr>
                         <td width="23%" valign="top" align="left">
                              <% if (bean.isAdvanced(cat) && bean.hasMultimediaImage(cat)) { %>
                                   <a href="link" onClick="javascript:invokeLink('<%= bean.getEncodedServlet("se.ibs.ns.icat.ItemCatalogueCategoryServlet", response) %>?CODE=<%= ToolBox.encodeURLParameter(cat.getCode())%>'); return false">
                                   <img border="0" src="<%= bean.getMultimediaImage(cat) %>"></a>
                        <% } else {%>     
                                   <img border="0" src="<%= resourcePath %>Catalog.gif">
                              <% } %>
                         </td>
                         <td class="IBSTextNormal" width="40%" valign="top">
                              <%= bean.getWebText(cat) %>
                         </td>
                  </tr>
                  <tr>
                         <td width="23%">
                         </td>
                         <td width="40%">
                         <% Vector mmLinks = bean.getMultimediaLinks(cat);
                      int mmLinksSize = mmLinks.size();     
                              for (int ml=0; ml<mmLinksSize; ml++){
                                   BAPCodeAndDescription mmLink = (BAPCodeAndDescription)mmLinks.elementAt(ml); %>
                                   <a class="IBSLink" href="<%= mmLink.getCode() %>" target="_blank"><%= mmLink.getDescription() %></a><br>
                         <% } %>
                   <% Vector webLinks = bean.getWebLinks(cat);
                        int webLinksSize = webLinks.size();
                        for (int wl=0; wl<webLinksSize; wl++){
                                   BAPCodeAndDescription webLink = (BAPCodeAndDescription)webLinks.elementAt(wl); %>
                                   <a class="IBSLink" href="<%= webLink.getCode() %>" target="_blank"><%= webLink.getDescription() %></a><br>
                        <% } %>
                         </td>
                  </tr>
                <%}%>
    </table>
    </div>
    <%@ include file="FuncPageLinks.jsp" %>
    <%@ include file="FuncPageEnd.jsp" %>
    </form>
    </body>
    </html>i hope someone could help me to understand this,
    thank you for your help

    You've probably already seen these, but here are a couple of links that may help.
    http://help.adobe.com/en_US/FlashPlatform//reference/actionscript/3/operators.html#array_a ccess
    http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/Array.html
    What's basically happening is that the "for" loop goes through each item in the array.  Don't be confused by the fact that two of the items in the array are Strings and one is an Integer - variable i being a String has nothing to do with the data type of the elements in the array.
    The following code:
    private function createLabels():void
         var myArray:Array = ['one', 'two', 3];
         for(var i:String in myArray)
              trace("i = " + i);
              trace(myArray[i]);
    gives the following results:
    i = 0
    one
    i = 1
    two
    i = 2
    3
    From that we can see that the "for" loop is assigning the index number of each array element, not the actual array element ('one', 'two', or 3) to the variable i.  So calling myArray[i] is the same as calling myArray[0] the first time through the loop.  This type of "for" loop is just a shorter way of doing the following, which produces exactly the same results:
    private function createLabels():void
         var myArray:Array = ['one', 'two', 3];
         for(var i:int = 0; n < myArray.length; i++)
              trace("i = " + i);
              trace(myArray[i]);
    Hope that helps.
    Cheers!

  • Trying to understand the basic concept of object oriented programming.

    I am trying to understand the basic concept of object oriented programming.
    Object - a region of storage that define is defined by both state/behavior.
    ( An object is the actual thing that behavior affects.)
    State - Represented by a set of variables and the values they contain.
    (Is the location or movement or action that is the goal that the behavior is trying to accomplish.)
    Variables- (What does this mean?)
    Value - (What does this mean?)
    Behavior - Represented by a set of methods and the logic they implement.
    ( A set of methods that is built up to tell's the how object to change it's state. )
    Methods - A procedure that is executed when an object receives a message.
    ( A very basic comand.For example the method tells the object to move up, another method tells the method to go left. Thus making the object move up/left that combination is the behavior.)
    Class - A template from which the objects are created.
    ( I am very confused on what classes are.)
    - The definitions of the words I obtained from the "Osborne Teach Yourself Java". The () statements are how I interperate the Mechanisms (I do not know if Thats what you call them.) interact with each other. I understand my interpretation may be horribly wrong. I will incredibly appreciate all the support I may get from you.
    Thank you

    Object oriented programming is a replacement for the older idea of procedural programming (you can research procedural programming in google). As I understand it, in procedural programming, you have a step by step set of function calls to accomplish some task. Each function receives a data structure, manipulates it, and passes it to the next function. The problem with this is that each function preforms some action for the overall task and can't easily be reused by some other task. Its also harder to read the flow of what is happening with raw data structures flying all over the place.
    In object oriented programming, an object calls a function of another object and receives back, not a data structure, but another object. Objects contain a data structure that can only be accessed by its functions. An object is not so much a sub component of a bigger task, as it is a service that any other task can use for any purpose. Also, when you pass an object to the caller, the caller can ask questions about the data structure via its functions. The developer doesnt have to know what the previous function did to the data by reading up on any documentation, or having to reverse engineer the code.
    I suggest the best way of learning this is to code something like a library object.
    A library object contains a collection of book objects
    A book object contains a collection of chapter objects
    A chapter object contains a collection of paragraph objects
    A paragraph object contains a collection of sentence objects
    A sentence object contains a collection of word objects.
    Add functions to each object to provide a service
    Example: A library object should have a:
    public void addBook(Book book)
    public Book getBook(String title)
    public boolean isBookInLibrary(String title)
    The key is to add functions to provide a service to anyone who uses your object(s)
    For example, what functions (service) should a paragraph object provide?
    It shouldn't provide a function that tells how many words there are in a sentence. That function belongs to a sentence object.
    Lets say you want to add a new chapter to a book. The task is easy to read
    if you write your objects well:
    Sentence sentence1=new Sentence("It was a dark and stormy night");
    Sentence sentence2=new Sentence("Suddenly, a shot ran out");
    Paragraph paragraph=new Paragraph();
    paragraph.addSentence(sentence1);
    paragraph.addSentence(sentence2);
    Paragraphs paragraphs=new Paragraphs();
    paragraphs.addParagraph(paragraph);
    Library library= new Library();
    library.getBook("My Novel").addChapter("Chapter 1",paragraphs).
    Now, lets say you want to have a word count for the entire book.
    The book should ask each chapter how many words it contains.
    Each chapter should ask its paragraphs, each paragraph should ask
    its sentences. The total of words should ripple up and be tallied at each
    stage until it reaches the book. The book can then report the total.
    Only the sentence object actually counts words. The other objects just tallies the counts.
    Now, where would you assign a librarian? What object(s) and functions would you provide?
    If written well, the project is easily extensible.

  • Trying to understand the Serialization interface

    Im trying to understand the Serialization of objects?
    As an example, I create a Library class that implements Serializable, that stores a collection of Book objects
    If I am only looking at saving a Library object to file, does the Book class require Serialization also or just the Library?
    I have read the API on serialization, no answer there, if it is it's not easy to understand or read into the API...

    There are some really important things to know about when doing serialization. For example one important thing to know about that not is mentioned here is that your serializable classes must define its own private static final long serialVersionUID because if you not do that will you not be able to deserialize (read in) the data you have saved later if you change anything in your serializable class. It is a bit tricky to manage files to which you have serialized different versions of your class, that is versions where you have added more serializable members to the class after you have serialized files. Well, it is not a problem if you don´t care if you have to type in all your saved data again every time you change anything instead of deserialize it (read it) from your file of course :)
    Situations like this may be handled if you define your own (private) writeObject(ObjectOutputStream) and your own readObject(ObjectInputStream) methods in your serializable class but there is a better a lot smarter way to handle this. Use of a serialization proxy! how to use that is described in the excellent book Effective Java 2nd ed. With a serialzation proxy for every serializable version of your class (where a version corresponds to a version of your class with differences in its number of serializable members) may your class deserialize data written from elder versions of your class also. Actually is it first since I read the last chapter of Effective Java that I think I have myself begin to understand serialization well enough and I recommend you to do the same to learn how to use serialization in practice.

  • Trying to understand Transferable

    Hello, I'm trying to write a drag-and-drop file uploading applet and am thus trying to understand the Transferable interface. I found some very clear source but no clear explanation of one point. I'm sure this information is commonly available; I apologize for being unable to find it and would appreciate a link.
    Running this code :
    public boolean importData(JComponent src, Transferable transferable) {
    println("Receiving data from " + src);
    println("Transferable object is: " + transferable);
    println("Valid data flavors: ");
    DataFlavor[] flavors = transferable.getTransferDataFlavors();
    DataFlavor listFlavor = null;
    DataFlavor objectFlavor = null;
    DataFlavor readerFlavor = null;
    int lastFlavor = flavors.length - 1;
    // Check the flavors and see if we find one we like.
    // If we do, save it.
    for (int f = 0; f <= lastFlavor; f++) {
    println(" " + flavors[f]);
    if (flavors[f].isFlavorJavaFileListType()) {
    listFlavor = flavors[f];
    if (flavors[f].isFlavorSerializedObjectType()) {
    objectFlavor = flavors[f];
    if (flavors[f].isRepresentationClassReader()) {
    readerFlavor = flavors[f];
    // Ok, now try to display the content of the drop.
    try {
    DataFlavor bestTextFlavor = DataFlavor.selectBestTextFlavor(flavors);
    BufferedReader br = null;
    String line = null;
    if (bestTextFlavor != null) {
    println("Best text flavor: " + bestTextFlavor.getMimeType());
    println("Content:");
    Reader r = bestTextFlavor.getReaderForText(transferable);
    br = new BufferedReader(r);
    line = br.readLine();
    while (line != null) {
    println(line);
    line = br.readLine();
    br.close();
    else if (listFlavor != null) {
    java.util.List list = (java.util.List)transferable.getTransferData(listFlavor);
    println( list + " Size " + list.size());
    else if (objectFlavor != null) {
    println("Data is a java object:\n" + transferable.getTransferData(objectFlavor));
    else if (readerFlavor != null) {
    println("Data is an InputStream:");
    br = new BufferedReader((Reader)transferable.getTransferData(readerFlavor));
    line = br.readLine();
    while (line != null) {
    println(line);
    br.close();
    else {
    // Don't know this flavor type yet...
    println("No text representation to show.");
    println("\n\n");
    catch (Exception e) {
    println("Caught exception decoding transfer:");
    println(e);
    return false;
    return true;
    which you'll agree is very clear, returns me a List of filepaths when I drop files on it. Perhaps naively, I was hoping to get the data itself.
    Obviously I can go the route of messing with security settings to allow the applet to open files (eeew) but I'm hoping the actual data is available from Transferable and I'm simply not understanding how to do it.
    Thanks for any tips.

    And don't forget to check this link:
    http://www.javaworld.com/jw-03-1999/dragndrop/jw-03-dragndrop.zip
    I think with few modifications you can get what you want.

  • Trying to understand hashCode( )

    Hello again, I'm trying to understand the hashCode( ) method. I have a textbook which describes it this way:
    "A hashcode is a value that uniquely identifies an individual object. For example, you could use the memory address of an object as it's hashcode if you wanted. It's used as a key in the standard java.util.Hashtable[i] class."
    Please forgive me if this emplies that I may be a bit slow with this, but this explanation is too vague for me to grasph what's going on here. Can someone thoroughly explain (in a non scientific way), how and why this method is used?
    Thanks in advance.

    I thought the examples I provided might give you an idea why the hashCode method is useful. I'll try one more brief one, and if that doesn't connect that spare wire to the light bulb over your head, then I'll have to agree with schapel and suggest that you study up on your CS theory.
    This will be a really crocked up example, and you could skirt some of the issues with better design, but it's a valid example nonetheless.
    You run a greenhouse or an arboretum or something. You've got 25,000 Tree objects (forget their subclasses for now). Trees have properties like species, name (I don't know why you'd name a tree--just bear with me), location, age, medical history. You're going to put your Trees into a java.util.Set, so you've got a collection with one reference to each tree. However, you're getting overlapping subsets of your trees from various sources--that is getAllElms() returns some trees that are also in getAllOlderThan(10). You need to combine all those results into a 1-each collection of Trees.
    When you go to add an Object to the Set, the Set has to first check if that Object is already present. The Set implementation could iterate over all its elements and call equals() to see if that Object is already there. Or, it could first get the hashCode (let's say you've implemented hashCode to return the xor of the species and the age). So, maybe 100 out of your 25,000 trees are 50 yeard old Elms. Internally, if the Set implementation keeps a mapping from hashCode to an array of Trees with that hashcode, then it only has to copmare to those 100 trees that match, rather than all 25,000.
    As I said, this is a cheezy example. One problem is that if trees are mutable, this Set implementation won't work, since the Set won't know that a Tree's internal values (and hence, possibly, its hashCode) have changed.
    Is is making any sense yet?
    Okay so please help me understand this rudimentary,
    logical reason for wanting to use a hashCode( )? Say
    I create a top level class called "Plant.java". Now
    from that class I create a subclass called Tree.java
    from which several other subclasses and objects are
    created. Help me gain a basic understanding of why
    and how the hashCode( ) method might be beneficial.
    (lol... I feel sort of like I've opened up a cool new
    electronic toy, I'm standing here with a "spare wire
    in my hand wondering what the heck this part is
    for?")
    Thanks again for your help. I really apprecitate it.

  • Java socket - unsure road to take!

    Hi all,
    We have an application requiring data transfer from a JSP Web application (socket client) and a stand-alone java application (socket server).
    This java stand-alone app communicates to an industrial microcontroller connected to the RS-232 serial port.
    When this java apps received a command from the JSP web app, it cannot service any other command from other uses, since there is just one RS-232 serial port on the computer. We would like to rely on the java & network environment to buffer additional commands receive simultaneously, as opposed to write code on the java socket server to handle this. In other works, our java stand-alone operates in an assynchronous, single-task mode.
    We are unsure which approach to take as far as java socket goes:
    1) simple socket server/client;
    2) multithread socket
    3) pooled
    Can anyone advise us.
    Thank you
    Trajano

    Hi Pete,
    1) Yes, we can have more than one user trying to access the micro-controllers, because we have in reality a network of micro-controllers connected to the single RS-232 computer port via a RS-485 to RS-232 converter;
    2) If a second user tries to issue a command to micro-controller, I would prefer for the java socket/environment to take care of the buffering, by just delaying the response, until the first user gets its command serviced
    3) If there is 1 user, him/her might issue several commands at the same time, by opening several JSP pages;
    4) No the controllers can service any instruction coming up at any time. The protocol is master/slave. The java app issues a request and the micro-controlle replies back and ready to accept any other request.
    ISSUE: My preference is for the system to take care of commands arriving at the socket server.
    This java app has two threads:
    1) Thread1 is the java socket server and upon receiving a command it will update three (3) properties:
    micro-controller address, command and product code
    2) Thread32 will be responsible for polling the 3 properties to check if they've changed. Upon detecting a change, it will build the data string and send to the RS-232 serial port.
    Any ideas/suggestions.
    Thanks in advance for any assistance.
    Regards

  • Creating java sockets behind proxy servers.

    Hi,
    I am trying to create a socket to an external server(i.e. a public server) from behind a proxy firewall, but the socket creation statement throws an IO exception. Can someone please let me know how to create sockets using proxy servers.
    TIA
    Shishir

    I tried using java.net.Proxy for the connection. But the socket to the proxy itself is not getting created. It throws the IllegalArgumentException.
    import java.io.*;
    import java.net.*;
    import java.net.Proxy.Type;
    public class Client {
    static Socket proxSocket = null;
    static PrintWriter out = null;
    static BufferedReader in = null;
    public static void main(String[] args) throws IOException {    
    try {
    System.out.println("Trying to create socket");
    InetSocketAddress proxyadd = new InetSocketAddress(InetAddress.getByName("148.87.19.20"),80);
    Proxy ps = new Proxy(Proxy.Type.HTTP,proxyadd);
    Socket proxSocket = new Socket(ps);
    out = new PrintWriter(proxSocket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(
    proxSocket.getInputStream()));
    } catch (UnknownHostException e) {
    System.err.println("Don't know about host: ...");
    System.exit(1);
    } catch (IOException e) {
    System.err.println("Couldn't get I/O for "
    + "the connection to: ...");
    System.exit(1);
    catch(IllegalArgumentException e)
    System.err.println("Unable to describe the proxy.");
    System.exit(1);
    }

  • Socket AS3 ( Receive File .TXT ) + Java Socket

    Hi,
    I have Java Socket sending .TXT file ( 10 MB ) . But the AS3 only gets 63 Kb . I do not understand the loss of bytes ...
    Souce Java :
    public void sendFile(String fileName) {
            try {
                //handle file read
                File myFile = new File(fileName);
                byte[] mybytearray = new byte[(int) myFile.length()];
                FileInputStream fis = new FileInputStream(myFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                DataInputStream dis = new DataInputStream(bis);
                dis.readFully(mybytearray, 0, mybytearray.length);
                OutputStream os = clientSocket.getOutputStream();
                byte[] fileSize = intToByte(mybytearray.length);
                byte[] clientData = new byte[(int) myFile.length() + mybytearray.length];
                System.arraycopy(fileSize, 0, clientData, 0, fileSize.length); // Copy to the file size byte array to the sending array (clientData) beginning the in the 0 index
                System.arraycopy(mybytearray, 0, clientData, 4, mybytearray.length); // Copy to the file data byte array to the sending array (clientData) beginning the in the 4 index
                DataOutputStream dos = new DataOutputStream(os);
                //dos.writeUTF(myFile.getName());
                //dos.writeInt(mybytearray.length);
                dos.write(clientData, 0, clientData.length);
                dos.flush();
    AS3 Source..
    private function onResponse(e:ProgressEvent):void {
      var file:File;
      var fs:FileStream;
      var fileData:ByteArray = new ByteArray();
      file = File.documentsDirectory.resolvePath("tmpReceive.txt");
      fs = new FileStream();
      fs.addEventListener(Event.CLOSE,onCloseFileReceive);
    if(_socket.bytesAvailable > 0) {
      while(_socket.bytesAvailable) {
      // read the socket data into the fileData
      _socket.readBytes(fileData,0,0);
      fs.open(file, FileMode.WRITE);
      // Writing the file
      fs.writeBytes(fileData);
      fs.close();

    Crypto streams, like CipherInputStream andCipherOutputStream, do not behave properly until you
    issue a close() call. So if you are going to do
    crypto, you will need to trap the close() before it
    reaches the underlying socket streams. This is
    because the close() method finalizes the cryptographic
    operation. (Flush() would make more sense, no idea
    why they did it this way). You do want to finalize
    the crypto for any given message, but you need to trap
    the close() before it hits the socket and ends the
    whole affair.
    I don't see anything about that in the bug database.
    No matter what streams you are using, if you aregoing to keep the socket open for multiple
    request-response round-trips, you need to very closely
    pay attention to how much data is being sent on each
    trip. Normally, you can fudge this a bit on a
    request-response because the close() call on the
    output stream will cause the receiving input stream to
    behave more or less properly. However, a flush() will
    not.Why not? I use that all the time with no problem.
    A good practice is to send the content-length of
    the message first, so the receiving input stream
    "knows" when to stop reading, does not block, and then
    can send its own bytes back the other direction.
    (Where the process is repeated).
    An alternative is to use two threads: read and write.
    The read recieves, parses, validates and then pushes complete messages to a queue.
    The write pulls messages from the queue, processes and send a result.
    A variation to the above is what happens when an invalid message is received. The server can ignore it, the read can send a error response, or the read can push a message to the queue which causes the write to send a error response.

  • The service bit "write enable" in Java Socket

    Hello,
    I am trying to communicate with a third party application and I am having some problems. I use a standard Socket connection, were my application is the Server (ServerSocket). The connection is established, but no data is transmitted.
    I talked with the guys behind this third party application, and they said that perhaps their application does not receive a "write enable" service bit of the tcp/ip protocol. I'm not a network wiz, so this is an unknown territory for me.
    So I ask you. What is this "write enable" tcp/ip service bit? Is this per default on in java socket connections? If no, how can I change this?
    Perhaps this is very basic knowledge, but I've googled a bit and have not found this "service bit".

    This could refer to something in their
    protocol which you aren't implementing correctly.Probably, but I believe they have "forgotten" to mention that it is required in our implementation.
    OTOH if you are the server the transaction would
    normally begin with a request from the client, not a
    write-enablement from the server.The defined protocol smelled fishy when reading the "whitepaper", but we had to accept it (politics).

  • C# socket and java socket

    hello
    i am a java programmer,recently we got a project,that need the c# app to communicate with java app ,i select the socket as intermediate.
    i notice that java socket term is divided into " blocking" and "non-blocking",the latter come from jdk1.4, the c# socket is devided into "synchronized" and "asynchronized" and both of them are blocking,
    in my project,i have tried synchronized c# socket coorperating to blocking java socket,it works well..but when i modify the c# app to ASYNCHRONIZED socket,my system DON'T works well,i don't know why? i can't find asynchronized socket in java,.i learn that nio socket is nonblocking, is it asynchronized?
    who can tell me what's is the best solution for the socket communication between java and c#?

    yes,i have read them,but it only tell me the communication between java apps,and DON'T tell me any clue about c# socket.

Maybe you are looking for