Java Socket Constructor

Hi All:
We all know that "Socket(String host, int port)" create a client socket which connecting to
the target host : port
however, which local port does it connect from? I guess it must be a random port from list of
available ports. but how can we find out which port is currently been used?
I thought another constructor Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
might help. but the following code :
" Socket connection = new Socket("www.google.com", 80, InetAddress.getByName("localhost"), 0);"
doesn't work either. can anyone spot the problem please

0 means ANY currently available port, what's wrong with choosing 0 to be the port number?
just because is not documented on the Java documentation? read http://books.google.co.uk/books?id=NyxObrhTv5oC&dq=java+network+programming&pg=PP1&ots=1d9JyFUpRY&sig=HPm47jAWjRHrMpZw0UTG2nM86bA&hl=en&prev=http://www.google.co.uk/search?hl=en&q=java+network+programming&btnG=Google+Search&sa=X&oi=print&ct=title&cad=one-book-with-thumbnail#PPA281,M1
before even recommend your so-called better book. by the way it was a firewall issue.I 'v got it solved now.
may be "didn`t work" is not efficient word to explain things, but it is better then
someone wrote down full of c.r.a.p, without saying anything useful at all.
I don`t understand why my question doesn`t make any sense. choosing random port at runtime rather then
giving a specific number, is a common programming technique, I thought it making a GREAT sense.
Edited by: Shanyangqu on Jan 21, 2008 3:38 AM

Similar Messages

  • 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]

  • Socket constructor problems

    I have a moderate amount of experience with Java, but am new to network programming. I am using the Socket class, but the client stalls at the line containing the Socket constructor. I have been all over the web, and have checked numerous code examples, but my code seems to check out. Here is the constructor and relevant code:
    final int LOAD_PORT = 7778;
    InetAddress addr = InetAddress.getByName("127.0.0.1");
    Socket socket = new Socket(addr, LOAD_PORT);
    I am trying to just get this to work with both the client and the server running on my machine to start with. I have some TextArea.append statements interspersed so that I know which line stalls, and the last .append statement that works is just before the Socket constructor line.
    If anyone might know what my problem is, please respond.

    I tried that and about a million other combinations.
    I finally figured the problem out about a week ago...
    I needed to upgrade to SDK 1.4.0 from SDK 1.3.1. I tested this program out on a system using 1.4 and it worked fine with no modifications at all. Then I went back to a 1.3 system, it didn't work, I downloaded and installed 1.4, tried it again, and it worked like a charm.
    Thanks for the reply, though,
    Tim

  • Java Socket on low bandwidths

    Hello!
    I am currently working on a project where we try to use Java technology (through Jini) over an HF radio link. That means we're working with bandwidths down to 75 b/s. And we are experiencing what we suspect is a timeout when we try to make a new Socket.
    What happends is we get a 'NoRouteToHostException: connection timed out', and it seems to us that this happends in the Socket constructor. That means we never get the chance to set the SO_TIMEOUT or other Socket parameters since the exception (seemingly) is thrown during Socket creation.
    This is mainly a problem on the lowest bitrate (75 bits per second), but we have also experienced this with 150 b/s. Not on a regular basis, though.
    We are about to write this off as being caused by some timeout in the Socket constructor which we have no chance to modify, but we would welcome any information that can help us understand this.

    75 b/sSo you get an effective rate of 9 bytes per second.
    That sounds like fun.
    Presume the IP packet size is 128 bytes And there is also a host lookup then it takes a minium of 4 packets. Which means 56 seconds to connect. And that is with no processing time. And no lost packets.
    Are you using a host name or just an IP? If the host name I believe you can do a lookup on that first and then use the IP. That would make a timeout less likely.

  • Using plain Java Sockets(not RMI) how..?

    hi!
    1. Using plain Java Sockets(not RMI) how can the client detect when its server
    goes down?
    There is a long time interval between client requests and the client wants
    to retain a live connection rather than disconnect after every reqest.
    Please also cc your reply to [email protected]
    Thanks,
    \Raghu

    If you try to send data when the host is gone, it throws an exception. I don'thow to check if it is alive though. I'm having the same problem right now.

  • 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

  • Java socket streams messing up

    iv wrote a games server and it uses java socket streams to send the messages back and forth between the game clients and the game server it self
    this all works great but when running and over about 5min its send over 1000 packets BUT
    it will crash iv found the reason is down to when reading the packets my parser is reading wrong part and grabbing a String part when it should be a INT
    now it should NEVER be reading this part of the packet so i put a trace on the packets coming in and ran it every packet was been read in perfect THEN just befor the crash TWO packets were merged together stright out from the socket stream this is y my packet reader was getting confused
    what im asking is can this happen in java sockets ? i thought they were bufferered so no matter how fast you send data it would always read it out in the same order ?? not sure how its merging these to packets
    is this possible of is my reader got an error in it altho works 95% of the time ??

    or do you have multiple buffered streams created from the same socket?

  • 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.

  • JAVA SOCKET TIMEOUT WHEN GENERATING PDF TO ADS SERVER

    We are currently getting the error when attempting to generate the PDF from the thin portal BI Reports and recieved the JAVA SOCKET READ TIME OUT error and
    applied adjustments to the notes
    934725 and 826419 by changing the timeout sessions to 300, but still get the same timeout errors:
    Note: We changed ADUSER user type and password, passed rpcData test, RFC HTTP external connections to ADS server...so we've came a long ways and here we are now with the timeout errors...
    Any ideals???

    Hi
    when you reset password please select checkbox for password never expires.
    see the following notes :
    1.Note 944221 - Troubleshooting if problems occur in forms processing
    2.Note 811342 - Time Out exception when rendering to Adobe document service
    thanks
    Gopal

  • 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).

  • Java sockets (peek functionality)

    Hi,
    how do i peek at a datagram, look into the data and accordingly
    decide whether to consume that datagram or leave it for later
    processing?
    Is this something Java sockets readily support OR do I need
    to implement some kind of store-for-later-processing
    please help
    Thanks.

    java.net.DatagramSocket doesn't have peek support in the API at this time - see 4102648.
    If you were to use a non-blocking DatagramChannel and register it with a Selector then you should be notification that a packet can be read. Okay, it doesn't give you the details - just that a packet is available but it may help in your environment.

  • Java sockets forwarding (redirect)

    Dear all
    I’m try to write a java sockets program which will accept VNC connection and forward it to another pc that has VNC server installed.
    That is: a client use vnc viewer connect to a JavaServer(where the sockets program run), the JavaServer accept this connection and forward it to the VNC server
    The reason doing this is because the client can only connect to the JavaServer, and the JavaServer has the ability to connect any host.
    I can manage to initiate the connection, and give the password that the VNC server request with the following code, but after this just before the viewer start to show the remote desktop, the sockets stuck on reading.
    can anyone help me out please.
    public void listen() throws Exception
    ServerSocket server=new ServerSocket(443, 5);
    System.out.println("Start Listen ...");
    while(true)
    Socket serverCon=server.accept();
    System.out.println("get Connection from: "+serverCon.getInetAddress());
    InputStream serverIn=serverCon.getInputStream();
    OutputStream serverOut=serverCon.getOutputStream();
    Socket targetCon=new Socket("192.168.1.3", 5900);
    InputStream targetIn=targetCon.getInputStream();
    OutputStream targetOut=targetCon.getOutputStream();
    byte[] buf=new byte[10240];
    int len;
    while(true)
    len=targetIn.read(buf);
    System.out.println(len);
    serverOut.write(buf, 0, len);
    len=serverIn.read(buf);
    System.out.println(len);
    targetOut.write(buf, 0, len);
    }

    Hi EJP
    Thanks for your reply,
    I did try to use threads with pipeStream,
    but it’s worse than the simple one,
    since it cannot even initiate connect between two side,
    the following is the sample code I use, which I leaned from here http://home.tiscali.nl/bmc88/java/sbook/029.html
    I can't found any more info regard to this topic on the internet, can you give me a hint.
    thanks a lot.
    public void listen2() throws Exception
      ServerSocket server=new ServerSocket(443, 5);
      System.out.println("Start Listen ...");
      while(true)
       Socket serverCon=server.accept();
       System.out.println("get Connection from: "+serverCon.getInetAddress());
       InputStream serverIn=serverCon.getInputStream();
       OutputStream serverOut=serverCon.getOutputStream();
       Socket targetCon=new Socket("192.168.1.1", 5900);
       InputStream targetIn=targetCon.getInputStream();
       OutputStream targetOut=targetCon.getOutputStream();
       PipedInputStream serverPin=new PipedInputStream();
       PipedOutputStream serverPout=new PipedOutputStream(serverPin);
       PipedInputStream targetPin=new PipedInputStream();
       PipedOutputStream targetPout=new PipedOutputStream(targetPin);
       while(true)
        ReadThread rt=new ReadThread("reader", targetIn, serverPout);
        ReadThread wt=new ReadThread("writer", serverPin, serverOut);
        ReadThread rt2=new ReadThread("reader", serverIn, targetPout);
        ReadThread wt2=new ReadThread("writer", targetPin, targetOut);
        rt.start();
        wt.start();
        rt2.start();
        wt2.start();
    class ReadThread extends Thread implements Runnable{
      InputStream pi=null;
      OutputStream po=null;
      String process=null;
      ReadThread(String process, InputStream pi, OutputStream po)
       this.pi=pi;
       this.po=po;
       this.process=process;
      public void run()
       byte[] buffer=new byte[1024];
       int bytes_read;
       try
        for(; ; )
         bytes_read=pi.read(buffer);
         if(bytes_read==-1)
          return;
         po.write(buffer, 0, bytes_read);
       catch(Exception e)
        e.printStackTrace();
    }

  • 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.

  • Java Sockets - help with using objects

    I am new to java sockets, and need to come up with a way to send a user defined instance of a class across a basic client/server application.
    I can not find out how to do this. I read the tutorials, but my class can not be serialized. How can I send/recieve this instance of a user defined class?

    right off the top of my head, doesn't serialver just spit out a UID for a given set of classes?
    To mark a class as Serializable, just implement the java.io.Serializable class - then you could use the readObject/writeObject methods of the ObjectInputStream/ObjectOutputStream classes.
    Good luck
    Lee

  • Java socket not handling the data packets properly

    I have created a small webserver application where i am receiving http requests from a siebel client. I am using content-length parameter to read the complete data in a buffer string using the command inputstreamreader.read. It works fine in all the cases, except when its used with a firewall. Some times the firewall splits a message into 2 and my logic fails as it doesn't find as many characters in the first packet as mentioned in the content length.
    My question is , how can i take care of these scenarios where a firewall is splitting the messages into multiple packets. why the java socket class is not handling the merging of these packets?
    any pointers are welcome.
    thanks

    Because that's the way TCP/IP works. read() gives you the data it can, and tells you how much was actually read. It's up to the application to reconstruct the application-level object. You could do something like this:    byte[] content = new byte[contentLen];
        int offset = 0;
        int remaining = contentLen;
        int currBytesRead = 0;
        while (remaining > 0 && currBytesRead != -1) {
          int currBytesRead = mySocketInputStream.read(content, offset, remaining);
          remaining -= currBytesRead;
          offset += currBytesRead;
        } (Warning: that's off the top of my head, uncompiled and untested. Use for demonstration purposes only!)
    Grant

Maybe you are looking for

  • GIF decoding

    This works on WinXP but not Linux. Why? It takes the first frame of an animated gif and writes a thumbnail.             GifDecoder d = new GifDecoder();                 try {                 fis = new FileInputStream(file);                          

  • How to stop syncing old podcasts?

    hi. my touch keeps downloading the old podcasts whenever i connect it to my pc. what should i do on itunes to make this process stop? i just keep on deleting them on the touch whenever i see it, but when i re-connect it, they appear again. thanks.

  • Problem in Stock Transfer

    Problem of Stock Tranfer : Branches not make any STO for transferring any faulty material to Mahape, Because some material which are physically hold to branches not show in SAP Stock Some material are dispatch from one branch to other branch, branch

  • HT1926 when trying to download itunes an error reading HRESULT pops up

    when I try to download itunes 10.6 an error pops up saying HRESULT and then after that another error pops up and says apple mobile device not verified?

  • PO number generate ( but in Hold)  for unreleased PR

    Hi Experts, I need a help on this Hold PO issue. If the PR is unreleased and if we convert this unreleased PR to Purchase Order system will through the error as PR noXXXXXX not released for ordering like that. But when you press the Hold button syste