Asynchronous socket programming in Java?

I am a C++ programmer, I just wonder how do I do asynchronous programming in Java?
In VC++, you can hook an event handler to the socket and the system will fire an event whenever there is data coming in to the socket. The event handler can then spawn a thread and handle the network message.
In Unix, you can use the select() function. This function will return whenever the indicated socket fires events. If nothing happens within the timeout period, the function simply returns.
What about in Java? I don't see any methods that allows you to hook an event handler to it. Is there anything like select() function in Unix?
Thanks so much.

There is something very much like C's select: selectors. I don't immediately know where to read more about them but google for things like "java selector example", "java nio tutorial", etc (NIO = new I/O, the library where selectors live.)
Another way to do async sockets in Java is by threading. That is the traditional way before New I/O. It's still a perfectly good and easy way, thanks to Java's easy threading. Downside is that it scales to only maybe 100-200 simultaneous connections per server (will depend on your operating system). For thread-based sockets check Sun's Java socket tutorial (first item when you google "java socket tutorial").

Similar Messages

  • Using socket programming in java stored procedure

    Hi there i am currently trying to develope a java stored procedure and place it in oracle and will try to use that procedure to send a message to a server but then it doesnt seems to work. is it possible?
    The server and the database is in the same pc and the server is just a small program listening to a port. Hope someone can help me thanks

    Hi there i am currently trying to develope a java
    stored procedure and place it in oracle and will try
    to use that procedure to send a message to a server
    but then it doesnt seems to work. is it possible?And what do you do with exceptions in your java proc?
    I haven't ever done it myself, but I would be very surprised if it wasn't possible. I also wouldn't be surprised to find out that you have to configure various things to allow it in Oracle itself.

  • Can we write X.25 program in Java

    hello friends
    can we write X.25 (protocal) program in Java , like we write socket program in Java.
    If we write means, kindly give a note, how to write.
    thank you
    seenu

    X.25 is connection oriented in that the sending party must initiate a connection to the receiving party. This connection
    establishes a virtual circuit that remains throughout the session. Because the virtual circuit is established at the time of
    connection, it is a switched virtual circuit (SVC).
    JTAPI is the set of classes, interfaces, and principles of operation that constitute a Java extension package in the javax.* name space. JTAPI implementations are the interface between Java computer telephony applications and telephony services, whether those services are implemented as software, as in the case of a soft PBX, or hardware. JTAPI defines the access to one or more of the following areas of functionality: Call Control, Telephone Physical Device
    Control,X.25
    my advice would be read and use JavaTM Telephony API
    it is at http://java.sun.com/products/jtapi/

  • Links / Books for Socket Programming

    HI Guys,
    Can any of you provide me some links or information on books about Socket Programming in Java. I have to deal with programming involving the client side to be in Java and the server which is in C. The topics which should be focused on are :
    1. Packet formation
    2. Packet parsing
    Thanks
    --J                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    There is a great book by a guy Elliotte Rusty Harold....I think it's called "Java Network Programming"
    Yeah here is the link to his website:
    http://www.elharo.com/

  • How to control tcp connection with java tcp socket programing ??

    Hi,
    I am connecting a server as using java socket programming.
    When server close the connection (socket object) as using close() method ,
    I can not detect this and My program continue sending data as if there is a connection with server.
    How to catch the closing connection ( socket ) with java socket programming.
    My Client program is as following :
    import java.io.PrintWriter;
    import java.net.Socket;
    public class client
      public client()
       * @param args
      public static void main(String[] args)
        Socket socket=null;
        PrintWriter pw=null;
        try
                          socket = new Socket("localhost",5555);
                          pw = new PrintWriter(socket.getOutputStream(),true);
                          int i=0;
                          while (true)
                            i++;
                            pw.println(i+". message is being send.");
                            Thread.sleep(5000);
        } catch (Exception ex)
                          ex.printStackTrace();
        } finally
                          try
                            if(pw!=null)pw.close();
                            if(socket!=null)socket.close();
                          } catch (Exception ex)
                            ex.printStackTrace();
                          } finally
    }

    I changed the code as following. But I couldn't catch the EOFException when I read from the socket. How can I catch this exception ?
    import java.io.BufferedReader;
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class client
      public client()
       * @param args
      public static void main(String[] args)
        Socket socket=null;
        PrintWriter pw=null;
        BufferedReader bufIn=null;
        InputStreamReader inRead=null;
        InputStream in=null;
        try
                          socket = new Socket("localhost",5555);
                          in = socket.getInputStream();
                          inRead = new InputStreamReader(in);
                          bufIn = new BufferedReader(inRead);
                          pw = new PrintWriter(socket.getOutputStream(),true);
                          int i=0;
                          while (true)
                            i++;
                            try
                              bufIn.readLine();
                              pw.println(i+". message is being send.");
                              System.out.println(i+". message has been send");
                            } catch (Exception ex2)
                              System.out.println(ex2.toString());
                              System.out.println(i+". message could not be send");
                            } finally
                            Thread.sleep(5000);
        } catch (EOFException ex)
                          ex.printStackTrace();
        } catch (InterruptedException ex)
                          ex.printStackTrace();
        } catch (IOException ex)
                          ex.printStackTrace();
        } finally
                          try
                            if(pw!=null)pw.close();
                            if(socket!=null)socket.close();
                          } catch (Exception ex)
                            ex.printStackTrace();
                          } finally
    }

  • A  Socket   Program Java

    Hello Dear Java Forums Team I'am Alfonso Franco who is reporting my socket program
    as http://www.javaworld.com without a port number assigned only the Input of www.javaworld.com more the following Code: System.out.printIn( " Enter a Host Name: ", + name) ;
    System.out.printIn( " Enter pin code number device: " + device) ;
    System.out.printIn( " Ours server is detecting a successfull connection " ) ;
    System.out.printIn( " Ours server sorry detect error didn't match name and number ") ;
    Please I'am looking for someone who will help me with my question is really this socket program works correctly if not give more reference to do it's improved . Thank you Team
    Alfonso Franco
    [email protected]

    Remove "if (input.ready())". readLine() will block, consuming zero cpu, until it gets data, EOF or an IOException.
    I've been programming sockets since mid-80's and I've never used something like socket.ready(). The normal way to do sockets is either to read() / readLine() or to select() / poll(). ready(), available() and such should come with big blinking warning labels.

  • Raw socket programming  is avilable in java

    hello,
    I want to reset my target device using device
    MAC address (not IP address).
    Is java support raw socket programming.
    can i send packets using MAC address in Java like C.
    I search in google. but, it shows there is no raw socket pgm support in java.
    any one help me this issue.

    JPCap

  • Java Swing and Socket Programming

    I am making a Messenger like yahoo Messenger using Swing and Socket Programming ,Multithreading .
    Is this techology feasible or i should try something else.
    I want to display my messenger icon on task bar as it comes when i install and run Yahoo Messenger.
    Which class i should use.

    I don't really have an answer to what you are asking. But I am developing the same kind of application. I am using RMI for client-server and server-server (i have distributed servers) communication and TCP/IP for client-client. So may be we might be able to help each other out. My email id is [email protected]
    Are you opening a new socket for every conversation? I was wondering how to multithread a socket to reuse it for different connections, if it is possible at all.
    --Poonam.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problem with socket programming(Vista)

    I'm not sure if this has something to do with windows vista.
    I wrote simple echo client and server programs and the client program contains these lines
    String hostname="172.16.54.22"; //My comp's IP
    int portNo=6666;
    mySocket=new Socket(hostname, portNo);
    Now the problem is that the client program is able to communicate with the server only when I run both of them in xp machines or if I run the server in vista and client in xp. The client is not able to connect to the server when both the client and server are running in a vista machine or if the server is running in xp and client in vista.
    It'd be nice if any of you could throw some light on this issue.
    PS:
    It doesn't work even if I turn the firewall off
    The programs work well when I give hostname="localhost" or hostname="127.0.0.1"
    Here are my programs
    //EchoClient.java
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class EchoClient
         public static void main(String args[])
              String hostname="172.16.54.25"; //My ip address
              int portNo=6666;
              //if(args[1]
              //PrintWriter out=null;
              Socket mySocket=null;
              BufferedReader networkIn=null;
              BufferedReader userIn=null;
              PrintWriter sockOut=null;
              try
                   mySocket=new Socket(hostname, portNo);
                   networkIn=new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
                   userIn=new BufferedReader(new InputStreamReader(System.in));
                   sockOut= new PrintWriter(mySocket.getOutputStream());
                   System.out.println("Connected to Echo Server\n");
                   System.out.println("Enter a series of lines (\"end\" to exit)\n");
                   while(true)
                        String myLine=userIn.readLine();
                   //     System.out.println(myLine);
                        if(myLine.equals("end"))
                             break;
                        sockOut.println(myLine);
                        sockOut.flush();
                        System.out.println(networkIn.readLine());
              catch(IOException exc)
                   System.err.println(exc);
              finally
                   try{
                   if(networkIn!=null) networkIn.close();
                   if(sockOut!=null) sockOut.close();}
                   catch(IOException exc){ }
                   EchoServer.java
    //EchoServer.java
    import java.io.*;
    import java.net.*;
    class EchoServer
         public static void main(String args[])
              int portNo=6666;
              ServerSocket serverSock=null;
              try
                   serverSock=new ServerSocket(portNo);
                   System.out.println("Echo Server Started\n\n");
                   while(true)
                        Socket clientSock=serverSock.accept();
                        new Thread(new EchoServerThread(clientSock)).start();
              catch(IOException exc)
                   System.err.println(exc);
         EchoServerThread.java
    //EchoServerThread.java
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class EchoServerThread implements Runnable
         public Socket clientSock;
         EchoServerThread(Socket sock)
              clientSock=sock;
         public void run()
              System.out.println("\nAccepted Connection from a Client");
              try{
              BufferedReader in=new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
              BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in));
              PrintWriter out= new PrintWriter(clientSock.getOutputStream());
                        /*In sockIn=new In(clientSock);
              Out sockOut=new Out(clientSock);*/
              String str;
              while((str=in.readLine())!=null)
                   out.println(str);
                   out.flush();
              System.out.println("Closing Connection from a Client");
              out.close();
              in.close();
              catch(IOException exc)
                   System.err.println(exc);
         

    Sorry everyone but I'd been giving a wong IP address thinking it's my own. The problem's solved.
    Thanks for the response Peter.

  • File descriptor leak in socket programming

    We have a complex socket programming client package in java using java.nio (Selectors, Selectable channel).
    We use the package to connect to a server.
    Whenever the server is down, it tries to reconnect to the server again at regular intervals.
    In that case, the number of open file descriptors build up with each try. I am able to cofirm this using "pfile <pid>" command.
    But, it looks like we are closing the channels, selectors and the sockets properly when it fails to connect to the server.
    So we are unable to find the coding that causes the issue.
    We run this program in solaris.
    Is there a tool to track down the code that leaks the file descriptor.
    Thanks.

    Don't close the selector. There is a selector leak. Just close the socket channel. As this is a client you should then also call selector.selctNow() to have the close take final effect. Otherwise there is also a socket leak.

  • Socket programming usin nio package

    hello frens i m new to socket programming
    i come to know that nio packaage provides more sophisticated and efficient API to deal with socket programming issue
    I need to know where i can get tutorial about socket programming using nio pacakage

    Try google
    http://www.google.co.uk/search?q=java+nio+tutorial

  • [Urgent]3G Socket programming

    May I use socket for 3G networks?
    I use the demo provided by the WTK2.5-Beta(NetworkDemo), it works well in the simulator. However, when I download the program to the mobile phone, it seems that the mobile phone that runs ServerSocket cannot create the socket ... all the 2 handsets use a 3G SIM card provided by a Hong Kong ISP smartTone ... What can I do?
    Please help~ provide any web page of codes, thanks very much!

    1.     We want to create a socket connection which can
    remain open and live for ever till it is closed. Is
    this possible in java socket programming?Yes, but it isn't practical in the real networking world. So your code had better be prepared to deal with network failures.
    2.     I am just wondering in order to communicate with
    the third party over the socket connection, does this
    other party requires to run something specific on
    their end? I am not able to understand how will my
    java code communicate with their server otherwise.It has nothing to do with java. Sockets send and recieve messages. The applications at either end, regardless of the language that they are written in, must handle those messages.
    3.     Can we send and receive data over the socket
    created and also is their specific format for the
    data? Yes.
    Can we send files of data over this connection?Yes. (Although I don't know why you would need to do that if you are doing credit card auths.)
    It would be great if someone can comment on these
    questions and also if possible please provide some
    code that can create socket connection.The tutorial.....
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • Socket connection between Java and C

    I want to establish socket connection between Java client and C server (on Unix). Can anybody tell how to do it? Will the socket created in client be available in server. I tried out but there was no response from the server.

    We too can't connect the daemon server written by "c". The phenomena is below.
    << Execution of this Question1.class >> ---------------------------------------
    [kazuyuki@CryptOne tmp]$ java Question1 E 1.2.3.4 MFrame.java 195.211.1.1 15021
    << Output message >> ----------------------------------------------------------
    Quetion1 : flg_ = E
    Quetion1 : key_ = 1.2.3.4
    Quetion1 : fn_ = MFrame.java
    Quetion1 : adr_ = CryptOne.localhost/195.211.1.1
    Quetion1 : port_ = 15021
    java.net.ConnectException: Connection refused
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:350)
         at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:137)
         at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:124)
         at java.net.Socket.<init>(Socket.java:268)
         at java.net.Socket.<init>(Socket.java:122)
         at Question1.UPLOAD(Question1.java:65)
         at Question1.main(Question1.java:155)
    << Question >> ----------------------------------------------------------------
    Why the event "java.net.ConnectException: Connection refused" has occured ?
    The server to connect from Question1 can accept the connection request from
    the client program coded by "c" program. We have written down the daemon server
    program by "c" code tcp/ip socket functions (socket, bind, listen, accept).
    Security manager admits the access from this Question1.class, we have checked.
    Would you like please answer this Connction refuse occurrence ?
                                                                     2002.05.18 11:50:00.0(JST)
                                                                     K.Masuda
    << Java client code>> -------------------------------------------------
         (c)Copyright     All rights reserved.
              K.Masuda     2002.05.18
                   << Question1.java >>
    import     java.lang.String;
    import     java.io.InputStream;
    import     java.io.OutputStream;
    import     java.io.DataInputStream;
    import     java.io.DataOutputStream;
    import     java.io.FileInputStream;
    import     java.io.FileOutputStream;
    import     java.io.IOException;
    import     java.io.FileNotFoundException;
    import     java.net.Socket;
    import     java.net.InetAddress;
    import     java.net.UnknownHostException;
    import     java.net.ConnectException;
    import     java.net.NoRouteToHostException;
    class Question1 {
         char               flg_;
         String               key_;
         String               fn_;
         InetAddress          adr_;
         int                    port_;
         Socket               sock_;
         Question1(
              char          flg,
              String          key,
              String          fn,
              String          adr,
              int               port
              flg_     = flg;     
              key_     = key;
              fn_          = fn;
              try{
                   adr_     = InetAddress.getByName( adr );
              catch( UnknownHostException e ){
                   e.printStackTrace();
              port_     = port;
    System.out.println( "Quetion1 : flg_ = " + flg_ );
    System.out.println( "Quetion1 : key_ = " + key_ );
    System.out.println( "Quetion1 : fn_ = " + fn_ );
    System.out.println( "Quetion1 : adr_ = " + adr_ );
    System.out.println( "Quetion1 : port_ = " + port_ );
         public void UPLOAD(
              try{
                   sock_     = new Socket( adr_, port_ );
                   UpLoad();
                   DnLoad();
                   sock_.close();
              catch( UnknownHostException e ){
                   e.printStackTrace();
              catch( ConnectException e ){
                   e.printStackTrace();
              catch( NoRouteToHostException e ){
                   e.printStackTrace();
              catch( IOException e ){
                   e.printStackTrace();
         public void UpLoad(
              byte[]                         buf          = new byte[ 512 ];
              int                              rlen;
              int                              wlen;
              try {
                   OutputStream          sos          = sock_.getOutputStream();
                   FileInputStream          fis          = new FileInputStream( fn_ );
                   DataInputStream          dis          = new DataInputStream( fis );
                   DataOutputStream     dos          = new DataOutputStream( sos );
                   while( ( rlen =     dis.read( buf, 0, buf.length ) ) >= 0 ){
                        dos.write( buf, 0, rlen );
                   dis.close();
                   dos.close();
                   fis.close();
                   sos.close();
              catch( IOException e ){
                   e.printStackTrace();
         public void DnLoad(
              byte[]                         buf          = new byte[ 512 ];
              int                              rlen;
              int                              wlen;
              try {
                   InputStream               sis          = sock_.getInputStream();
                   FileOutputStream     fos          = new FileOutputStream( fn_ + ".cry" );
                   DataInputStream          dis          = new DataInputStream( sis );
                   DataOutputStream     dos          = new DataOutputStream( fos );
                   while( ( rlen =     dis.read( buf, 0, buf.length ) ) >= 0 ){
                        dos.write( buf, 0, rlen );
                   dis.close();
                   dos.close();
                   fos.close();
                   sis.close();
              catch( IOException e ){
                   e.printStackTrace();
         public static void main(
              String[] args
              char[]     chrs     = ( new String( args[ 0 ] ) ).toCharArray();
              Question1     clnt     = new Question1(
                                                                     // E or D
                                            chrs[ 0 ],
                                            args[ 1 ],               // key string
                                            args[ 2 ],               // file to be processed
                                            args[ 3 ],               // IP address
                                                                     // port
                                            Integer.parseInt( args[ 4 ] )
              clnt.UPLOAD();
    }

  • Never programmed with Java

    Hello
    I have never programmed with Java, and dont know, what i can do, I use PHP, but, i am only a novice at it.
    I was wondering, is it possable to get data from a page, and put it into an image? if there is no data from the page, it will ask for the data to be added, and this will update every so often?
    Also, Most of you know about google maps, where you can search for something, well, can i do this same thing in java, have a map, not of the earth, but for a game, and make it easy to add different parts, so that we can search for it, and people can find it easy to look for what they are looking for?

    I think Google Maps is programmed in JavaScript using AJAX (short for Asynchronous JavaScript and XML) and is what as known as a web application. Google has released an API (still in beta) for working with Google Maps. The webpage for this API is http://www.google.com/apis/maps/. More about the development facilities Google provides can be found at http://code.google.com/.
    I've never read the source code to Google Maps before (a lot of which is available by just viewing the source code of the Google Maps webpage, which can be done by clicking, View > Source in Internet Explorer and View > Page Source in Mozilla Firefox), however I don't think it is a terribly complex application (this does not mean, however, that the source code is easy to read). I think the way it works is by requesting individual images as needed from the Google server and piecing them together on the client side (i.e. in the browser). Basically what you would need to do to use their existing code is to replace all requests made to the Google server with requests to a server of your own and have the server return the corresponding images. This might not be particularly easy to do.
    In my opinion, a better approach is just to write your own custom application (probably in Java) which simply mimics the behavior of Google maps, except with your own custom images. This way, you don't have to reverse engineer an entire web application before beginning to write one.
    Writing your own application for this purpose is not as difficult as it sounds, especially not in Java. Once understanding the basics, you will not be too far off from being able to write your application.
    Let's start with the most basic program (this program would be located in a file called Program.java):
    public class Program {
       public static void main(String[] args) {
    }This program simply starts, does nothing, and exits. I will explain this piece of code line by line, but first, I would like to gauge how much you already know to figure out how best to explain this. Have you used classes in PHP before?

  • RESTFUL Web Services vs Socket Programming Performance

    Hi guys,
    I will have an application which will have a service serving about to 30 million users/day and a mean of 5 requests/user.
    It means that there will be about 150 million requests per day. I will have two servers behind a load balancer and my clients will be both Java and C++.
    I think to implement RESTFUL Web Services but afraid of performance issues.
    Did you have a knowledge about the performances of web service and socket programming in such a high loaded project?
    Tnx.
    Ayberk

    ayberkcansever wrote:
    Hi guys,
    I will have an application which will have a service serving about to 30 million users/day and a mean of 5 requests/user.
    It means that there will be about 150 million requests per day. I will have two servers behind a load balancer and my clients will be both Java and C++.
    I think to implement RESTFUL Web Services but afraid of performance issues.
    Did you have a knowledge about the performances of web service and socket programming in such a high loaded project?It depends on the CPUs, RAM, disks, and network configurations of those servers.
    It depends on how the requests are distributed throughout the day.
    It depends on how big the requests are and how big the responses are.

Maybe you are looking for

  • How can I transfer my ipod touch itunes music to my Nexus 7?

    I want to be able to listen to the music that is on my Touch version 2 or 3 to my Nexus 7 tablet and go into the store to get more and manage my account.  I is possible and how do I do it?  Thanks

  • How do I trash movies from iTunes?

    Can anyone tell me how to trash .mov's, etc from my iTunes? I'm a Mac user. I trashed the files, but the movies are still in my iTunes (app)? FWIW, I cannot believe Apple has made this such a difficult task?

  • MIN Value that ignores 0

    Hello, experts - need your help. I have KF defined as MIN.  When I run BEX report for the lowest level (customer, material, time) I see a lot of 0 which is fine.  When I try to aggregate to the next level (material, time) it still shows 0. How do I a

  • Cost Centre report that shows all Tax Codes

    Hi there, We're trying to run a cost centre report that shows the tax codes relating to all expenditure, but Tax Code isn't an option in KSB1.  Is there a way that it can be imported, or another report that we can use? We need the tax code in order t

  • Is it true that apple will fix your products once for free ?

    Is it true that apple will fix your products once for free ? my iphone  just turned off last night and wont turn back on...