Timer, socket, and thread

I need to write a code that will open and write on/to a socket in less than two minutes. what classes should i have? I know I need the timer and socket, but which one should i use first? open a socket first than create a timer, or the other way? I'm new to this all OO stuff

I need to write a code that will open and write on/to
a socket in less than two minutes. ???
what classes
should i have? I know I need the timer and socket,
but which one should i use first? open a socket first
than create a timer, or the other way? I'm new to
this all OO stuffhttp://java.sun.com/docs/books/tutorial/
http://java.sun.com/docs/books/tutorial/essential/concurrency/
http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Tech/Chapter08/timers.html
http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

Similar Messages

  • Implementing sockets and threads in a jframe gui program

    Hi, I am trying to find a solution to a problem I am having designing my instant messenger application.
    I am creating listening sockets and threads for each client logged into the system. i want to know if there is a way to listen to other clients request from the main gui and then if another client tries to establish a connection with me for example, a thread is created for that client and then my chat gui opens automatically has soon has the other client sends his or hers first text message to me.
    I am relatively new at socket programming has I am currently studying along this area. I know how to create threads and sockets but I am having trouble finding out a solution to my problem. Here is the code that I have done so far for the listening method from my main gui, and the thread class of what I have done so far.
    listening socket:
         private void listeningSocket()
                ServerSocket serverSocket = null;
                boolean listening = true;
                try
                    //listen in port 4444;
                    serverSocket = new ServerSocket(4444);
                catch(IOException x)
                    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
                while(listening)
                    client_thread w;
                    try
                       w = new client_thread(serverSocket.accept(), jTextArea1);
                       Thread t = new Thread(w);
                       t.start();
                    catch(IOException x)
                         JOptionPane.showMessageDialog(null, "error, cannot start new thread", null, JOptionPane.ERROR_MESSAGE);
            }thread class:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.event.*;
    * @author jonathan
    public class client_thread extends Thread
         //define new socket object
        private Socket client_user = null;
        private JTextArea textArea;
        public client_thread(Socket client_user, JTextArea textArea)
            this.client_user = client_user;
            this.textArea = textArea;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured, messege was not sent";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   textArea.append(messege);
            catch (IOException e)
                //error messege
                JOptionPane.showMessageDialog(null, error, null, JOptionPane.ERROR_MESSAGE);
    }

    Seems like all you need to do is create a new dialog for each socket that is established. Your current design looks like it will attempt to use the same textarea for all the sockets.
    I would say in your thread class do the following:
    MyConversationDialog dialog = new MyConversationDialog();
    while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   dialog.setVisible (true);
                   dialog.addMessage (message);
                }

  • Sockets and thread communication multiplexing?

    Hello,
    I need to implement a server which will have a maximum of 10 clients connected.
    I wanted to go for classic blocking I/O because I won't have much clients.
    My problem is that even if I accept() some sockets and then create a thread for each socket,
    then I still need to communicate some data to the other threads, problem is that I am blocked
    on the read() operation, how could I address this problem?
    I mean, lets say I am thread1 and blocked on read() on my socket, now thread7 wants to tell
    me something like a chat message coming from client he handles, how could thread7 manage
    to wake thread1 and send him a message somehow?
    I do not want to deal with NIO stuff if possible because I do not need to scale, I just have a
    problem because I am stuck on the read.
    I will run on Windows.
    Thanks for help.
    Edited by: Marzullo on Jul 15, 2010 1:05 PM

    Fully answered in [your other thread|http://forums.sun.com/thread.jspa?threadID=5445070&messageID=11020688#11020688].
    Please don't multipost, as it can lead to people wasting their time repeating others' answers.

  • Problem with socket and Threads

    Hi,
    I have coded a package that sends an sms via a gateway.
    Here is what is happening:
    * I create a singleton of my SMSModule.
    * I create an sms object.
    * I put the object in a Queue.
    * I start a new Thread in my sms module that reads sms from queue.
    * I connect to sms gateway.
    * I send the sms.
    * I disconnect from socket! This is where things go wrong and I get the following error (see below).
    I have a zip file with the code so if you have time to take a look at it I would appreciate it.
    Anyway all hints are appreciated!
    //Mikael
    GOT: !LogoffConf:
    mSIP Kommando var: !LogoffConf
    CoolFlix log: MSIPProtocolHandler;setLoggedin(false)
    We got LogOffConf
    Waiting ......for thread to die
    java.net.SocketException: Socket operation on nonsocket: JVM_recv in
    socket input stream read
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:116)
    at
    sun.nio.cs.StreamDecoder$CharsetSD.readBytes(StreamDecoder.java:405)

    Off the top of my head, probably the garbage collector cleared your SMSModule coz all classes loaded through other classloaders will be unloaded when that classloader is unloaded.
    mail in the code if you want me to look at it with greater detail.

  • Socket and threads.

    I have written a socket client and a socket server. The client sends a directory name and the server sends directory files and their content. The client asks for files every five seconds (it has to be made once every day, but for trials I have reduced the time), so I have written a thread to made the client sleep for that time. The problem appears after looping fifty or sixty times, when the socket, which does not die, stops making its work (files are not send any more). I really thank every answer.

    Please be clear. What "stops work" the client or the server? Can you post the relevant code that is "looping fifty or sixty times"?

  • Socket and Thread Question?

    I have a Server/Client app where the Client connects to the server and the server accepts the Client and starts a new thread for each client.
    Then the Server Thread waits for the Client to contact.
    I set the timeout on the Server socket to 30 seconds.
    but the Client could sit there idle for much longer.
    So on the client side i used a timer to send "-1" every 5 seconds.
    That way if the Server Thread times out i know the Client is not there and end the thread and close everything.
    Now on the client side i may send several strings in a row to the server so i do not want my "-1" timer (i'm still here) messages to get intermingled with regular Client messages so i set up a boolean variable like so:
        volatile private boolean out1busy = false;
        private synchronized boolean getOut1busy(){
         return out1busy;
        private synchronized void setOut1busy(boolean on){
         out1busy = on;
        }then before using the socket i do this:
            while (getOut1busy()) try { Thread.sleep(40); } catch (InterruptedException ex) {}
            setOut1busy(true);
            lobbyOut.println("-1");
            setOut1busy(false);I have been running this for over a year and have personally never had a problem but have had rare clients testing say their comp has suddenly bogged down and it seems like they are describing what might happen if Out1Busy is set to true and not set back to false.
    ive checked my code and like i say it has never happened to me BUT i feel like what i am doing here is not the right way and there is probably a much better way to accomplish this. It is the only place in my code i see the chance of an infinate loop occuring.
    So regardless of whether or not it is even causing a problem can anyone tell me if it might cause a problem and a better way to do it.

    how about this.
    everywhere that i send data to the server that is not already on the event dispatch thread i just put in an invoke later which wold execute it on the eventdispatch thread.
    that way all communication with the server would be done on the event dispatch thread.
    so if i click a button that sends several strings right in a row it would complete before the "-1" im still here message sent at the same time goes through.
    so even if i had two bits of code that send several strings that need to be received in a row they would not get intermingled as long as they were both executed within a invokelater or already executed on the event dispatch thread (like a mouse clicked or action performed)
    so in my case here i always contact the server in either a state changed, action performed, or mouseclicked except for the "-1" im still here message.
    are alll these (state changed, action performed, or mouseclicked) executed on the event dispatch thread?
    i just put the "-1" in an invoke later and take out all the sleep and outbusy variable stuff.

  • Socket and Thread Problem

    When reading an Inputstream received after a connection has been established (throught a Socke connect) between a Server ands a Client , messages are being lost when a wait method is call. A client sents message which have to be processed and response sent back to the client . The message are encoded and as the code below shows each message ends with a '":" .Not only one message is sent at a time. and when messages are sent the client sometimes expect replies. This means that when a message is read , it be being processed by a Processor and until the reply has be sent this the thread reading the messages has to wait. when a reply is sent and the thread is waken up, the remaining the messages in the Input stream gets lost but the loop is not also exited since the end of the file is never reached.
    Solution:
    1. read a command message. if you find end of message, process the message and wait until you are notify and continue with the next command line
    public class Sender extends Thread {
         private Socket socket;
         private Processor processor = newProcessor();
         private boolean DEBUG = false;
         public Sender (Socket socket) {
              super();
              this.socket = socket;
              start();
         public void run() {
              while (true) {
                   if (processor .getStateOfProcess()&& socket != null) {
                        InputStream input = null;
                        try {
                             input = socket.getInputStream();
                             if (processor .dispatchMessage() != null) {
                                  socket.getOutputStream().write(
                                            CacheManager.dispatchMessage());
                                  processor .ClearMessage();
                        } catch (IOException ex) {
                        int i = 0;
                        char oldChar = ' ';
                        char c = ' ';
                        StringBuffer buffer = new StringBuffer();
                        try {
                             while ((i = input .read()) != -1) {
                                  c = (char) i;
                                  buffer.append(c);
                                                    if (c == ':' && oldChar != '\\') {
                                       processor .process(buffer.toString());
                                       buffer = new StringBuffer();
                                       c = ' ';
                                                              try {
                                            synchronized (this) {
                                                 wait();                         
                                       } catch (InterruptedException e1) {
                                                       if (processor.dispatchMessage() != null) {
                                            socket.getOutputStream().write(
                                                      CacheManager.dispatchMessage());
                                            processor.ClearMessage();
                                  oldChar = c;
                                    } catch (IOException e) {
       public void wakeup() {
              synchronized (this) {
                   notify();
    } This thread leaves that wait when the wakeup method is called in the Processor class.
    Question
    can some one help me figure out way and where the messages are being lost after the first message has been processed. why can the other message not be seen even other messages are still sent.
    What can be a possible solution
    thanks

    I didn't follow all of that, but I can see one serious error in your concurrent. You should always test the condition you're waiting for inside the synchronized block - otherwise you can't be certain that wait() is called before the corresponding notify() / notifyAll() call.

  • Socket and Thread Explanation

    I'm a little confused on the Socket stuff. I read some tutorials but wanted to make sure I understand. I'm using a simple client/server chat app as a reference.
    First the ServerSocket is just a connection to the port you want to listen on... I understand that. Is the Sockets... Socket s = ss.accept(); a tunnel to the port for data to travel on?
    Second.. When you create a Thread. This is the information that travels on these sockets? If that's the case I understand... But I have one question relating to some chat code I can't quite figure out.
    The simple chat program conists of a ChatServer, ServerThread and a Client.
    in the ChatServer it creates a ServerSocket and later on it looks for new connections for clients and then creates a ServerThread. What the heck is this for. From the code in the ServerThread it just handles incoming data and sends them back out. OK.
    But in the Client... it connects to this port and then creates it's own thread i.e. new Thread(this).start();
    Why ServerThread and then a Thread from the Client... Shouldn't there just be one?
    Sorry, I just can't get this.

    I'm a little confused on the Socket stuff. I read
    some tutorials but wanted to make sure I understand.
    I'm using a simple client/server chat app as a
    reference.
    First the ServerSocket is just a connection to the
    port you want to listen on... I understand that. Is
    the Sockets... Socket s = ss.accept(); a tunnel to
    the port for data to travel on?when the accept() method called, the server socket will start listening to the port for any connection. Once a connection established, this method will return a connected socket.
    >
    Second.. When you create a Thread. This is the
    information that travels on these sockets? If that's
    the case I understand... But I have one question
    relating to some chat code I can't quite figure out.A new thread was created here to that this thread can handle the socket return by the serversocket independenty to the main thread. Mainly server code will do this so that the main thread can continue to listening to other new connection agains while this newly created thread will handle any communication between a connected client and server.
    The simple chat program conists of a ChatServer,
    ServerThread and a Client.
    in the ChatServer it creates a ServerSocket and later
    on it looks for new connections for clients and then
    creates a ServerThread. What the heck is this for.
    From the code in the ServerThread it just handles
    incoming data and sends them back out. OK.
    But in the Client... it connects to this port and then
    creates it's own thread i.e. new Thread(this).start();Well, i dun know how the code for the client look like... but guessing that the client was implements Runnable. So, in the main method, it spawn a new thread and pass this class for this new thread to handle while the main thread maybe continue to do other things or just end after finish.
    >
    Why ServerThread and then a Thread from the Client...
    Shouldn't there just be one?
    Sorry, I just can't get this.Well, hope my explaination was clear enough... :P

  • Socket and Thread fun

    I am currently playing around with a, MUD like, program.
    I have 2 classes, server class who's main function is to listen to the port and create a new client class with the value of the incomming socket.
    The client class extends Thread, and pretty much just processes the input from the client socket.
    Now this is all good until I wanted to have multiple clients and have them talking to each other. I thought that having a Vector and storing the sockets in another class was the way to go. But whenever I refer to Vectors and Sockets I get the following runtime error :
    java.lang.NullPointerException
    at Controller.addSocket(ClientConnection.java:62)
    at ClientConnection.run(ClientConnection.java:35)
    Where line 35 is sending the socket to the class that adds it to the Vector, and 62 is trying to add the Socket to Vector.
    What am I doing wrong? Is there a better way of doing it, and if so a link to an example would be good.
    Cheers
    Shane

    From the stack traces, it is saying that the Controller is a null object. Probably you forgot to call on new Vector(), or you declared it twice in the constructor. There could also be a possibility that the socket passed to it was null.

  • Multi channel design issue - sockets and threads

    How are multiple channels handled in a chat program? Does the server separate the channels by having a port open for each channel, or is it done some other way?
    Thanks

    Yes it is possible. A user is logged on as long as the applet has a socket connection that has passed the login phase.
    Keep a server on the web site that handles the chat stuff. If you want to show some statistics like the users logged on, you can access the server from your local web site and ask him what's going on.
    You can do this with an administrative command set (your statistics module has to login to the server just like a chatter), with a special tcp port or with thread communication. In the latter case server and servlet would have to reside in the same JVM which is not really trivial...
    Another approach is to write the statistics into a shared file, and read this file from your web server.
    -- Stephan

  • Socket and Thread

    Hi,
    I am debugging a solution which had a filesend
    and dolisten method in the workchat project
    client: Project WorkChat
    https://docs.google.com/uc?authuser=0&id=0B3IOYEdd-pYSWVVtRzNHTGsxSjQ&export=download
    run the server before running this project
    and change the ip in the config point it to the server
    Also press enter in the right-top text box after typing the username,to start chat
    Double click to open private chat with another user.
    Drag and drop on user to send file
    server:
    https://drive.google.com/uc?authuser=0&id=0B3IOYEdd-pYSRjFyY0tKNmQ1bGc&export=download
    It is tough to test this solution and repair its filesend feature..
    Somehow it did work ,,but something went wrong of missing..
    I want to debug it and know what's not working in the filesend/dolisten methods.
    The rest of the code was derived from a vbsocket library which may now be unavailable through the MSDN
    Regards.
    Please remember to mark the replies as answers if they help and unmark them if they provide no help , or you may vote-up a helpful post

    Hello,
    I agree with Eason - you'd need to ask Google for help.
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog:http://unlockpowershell.wordpress.com
    My Book:Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C40686F746D61696C2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • RE:Socket muxer threads

    i am facing the issue where thread dump shows that Socket muxer threads are blocked where i am getting the load average as 3.5 and GCs are 4sec i am using the Sun JVM 1.5_19 and RHEL 5 does JVM upgradation bring the load average and GCs down
    Thanks
    Karan

    i can see the lot of parallel nursery GC and then occasionally Full GCs that is good actually as the processor would be with the application for most of the time it is clearing almost 800MB at the Full GC but we are seeing 4sec GC on an average and the loadaverage is above 4 we have 4cpus i think the loadaverage is acceptable as it 4*1.1 =4.4 but the response time is higher we want it to bring down is there anyway we can bring the GC we are using the parallel GC with Sun JVM 1.5_19
    Thanks
    Karan

  • Nasty memory leak using sockets inside threads

    In short, any time I create or use a socket inside a worker thread, that Thread object instance will never be garbage collected. The socket does not need to be connected or bound, it doesn't matter whether I close the socket or not, and it doesn't matter whether I create the Socket object inside the thread or not. As I said, it's nasty.
    I initially encountered this memory leak using httpclient (which creates a worker thread for every connect() call), but it is very easy to reproduce with a small amount of stand-alone code. I'm running this test on Windows, and I encounter this memory leak using the latest 1.5 and 1.6 JDK's. I'm using the NetBeans 5.5 profiler to verify which objects are not being freed.
    Here's how to reproduce it with an unbound socket created inside a worker thread:
    public class Test {
         public static class TestRun extends Thread {
              public void run() {
                   new Socket();
         public static void main(String[] strArgs) throws Exception {
              for(;;) {
                   (new TestRun()).start();
                   Thread.sleep(10);
    }Here's how to reproduce it with a socket created outside the thread and used inside the worker thread:
    public class Test {
         public static class TestRun extends Thread {
              Socket s;
              public TestRun(Socket s) { this.s = s; }
              public void run() {
                   try {
                        s.bind(new InetSocketAddress(0));
                        s.close();
                   } catch(Exception e) {}
         public static void main(String[] strArgs) throws Exception {
              for(;;) {
                   (new TestRun(new Socket())).start();
                   Thread.sleep(10);
    }Here's how to reproduce it implementing Runnable instead of extending Thread:
    public class Test {
         public static class TestRun implements Runnable {
              public void run() {
                   Socket s = new Socket();
                   try { s.close(); } catch(Exception e) {}
         public static void main(String[] strArgs) throws Exception {
              for(;;) {
                   (new Thread(new TestRun())).start();
                   Thread.sleep(10);
    }I've played with this a lot, and no matter what I do the Thread instance leaks if I create/use a socket inside it. The Socket instance gets cleaned up properly, as well as the TestRun instance when it's implementing Runnable, but the Thread instance never gets cleaned up. I can't see anything that would be holding a reference to it, so I can only imagine it's a problem with the JVM.
    Please let me know if you can help me out with this,
    Sean

    Find out what is being leaked. In the sample programs, add something like this:
        static int loop_count;
            while (true) {
                if (++count >= 1000) {
              System.gc();
              Thread.sleep(500); // In case gc is async
              System.gc();
              Thread.sleep(500);
              System.exit(0);
            }Then run with java -Xrunhprof:heap=sites YourProgram
    At program exit you get the file java.hprof.txt which contains something like this towards the end of the file:
              percent          live          alloc'ed  stack class
    rank   self  accum     bytes objs     bytes  objs trace name
        1  0.47%  0.47%       736    5       736     5 300036 char[]
        2  0.39%  0.87%       616    3       616     3 300000 java.lang.Thread
        3  0.30%  1.17%       472    2       472     2 300011 java.lang.ThreadLocal$ThreadLocalMap$Entry[]
        4  0.27%  1.43%       416    2       416     2 300225 java.net.InetAddress$Cache$Type[]See, only three live Thread objects (the JVM allocates a few threads internally, plus there is the thread running main()). No leak there. Your application probably has some type of object that it's retaining. Look at "live bytes" and "live objs" to see where your memory is going. The "stack trace" column refers to the "TRACE nnnnn"'s earlier in the file, look at those to see where the leaked objects are allocated.
    Other quickies to track allocation:
    Print stats at program exit:
    java -Xaprof YourProgram
    If your JDK comes with the demo "heapViewer.dll" (or
    heapViewer.so or whatever dynamic libraries are called on your system):
    java -agentpath:"c:\Program Files\Java\jdk1.6.0\demo\jvmti\heapViewer\lib\heapViewer.dll" YourProgram
    Will print out statistics at program exit or when you hit Control-\ (Unix) or Control-Break (Windows).

  • Problem with JNI and Tomcat (and threads???)

    Howdy,
    Here is the issue - I would like some help on HOW to debug and fix this problem:
    2 test use cases -
    1)
    a)User goes to Login.jsp, enters user and password
    b) User submits to LoginServlet
    c) login calls JNI code that connects to a powerbuilder(Yes I know this is ugly) PBNI code module (this is a .dll) that authenticates the user with the database
    d) the servlet then redirects to another .jsp page
    e) user then submits to LogoutServlet - also a JNI call to a powerbuilder PBNI code module
    f) REPEAT STEPS a-e over a few times (inconsistent) and then the call to the JNI code hangs
    2)
    a) users does NOT goto Login.jsp, but rather calls LoginServlet and passes the userid and password as GET parms
    b) user does NOT get redirected to a page (redirect code commented out)
    c) user calls LogoutServlet
    d) repeat steps a-c at will and no failure, no hanging
    The only difference is that in case 1 (with JSP), there is a redirect and it afffected the JNI call by haniging inside JNI code.
    In case 2 (without JSP) there is still a JNI call, but it does not hang. In addition, when it hangs and I stop Tomcat, the logs show cleanup entries that say:
    Oct 19, 2004 9:17:09 AM org.apache.catalina.core.StandardWrapper unload
    INFO: Waiting for 1 instance(s) to be deallocated
    Oct 19, 2004 9:17:10 AM org.apache.catalina.core.StandardWrapper unload
    INFO: Waiting for 1 instance(s) to be deallocated
    Oct 19, 2004 9:17:11 AM org.apache.catalina.core.StandardWrapper unload
    INFO: Waiting for 1 instance(s) to be deallocated
    Is this a threading issue in Tomcat???
    On would assume that the JNI code is not cleaning up after itself, but I don't believe this is the case,
    and even if it was, why would I get the tomcat log cleanup entries above???
    What do those cleanup entries imply about the state of Tomcat????

    hi ,
    I met the same problem this morning, and searched the www.google.com in order to solve it, as a result, your article was shown on my screen. :)
    Till now I have read some technical information and solved my problems. Maybe the solution be useful to you:
    ==============================
    error message : (Environment : Tomcat 5, Windows 2003, Mysql5)
    2006-3-29 11:53:48 org.apache.catalina.core.StandardWrapper unload
    message: Waiting for 2 instance(s) to be deallocated
    ==============================
    cause: the number of connection to database exceeded.another word,too many connections.
    ==============================
    solution: close the connection when it becomes useless for your program. :)
    ==============================
    ps. Sorry for my weak English . hehe ....

  • Can I use my external HD for Time Machine and still use it for storage?

    I have a 1TB external HD and my computer has yet to arrive. I was planning on backing it up via Time Machine and I'm wondering if my external HD will still be useable as a storage device once I pair it with Time Machine.
    There's no way the backup will take up the full 1TB of space, so I'm hoping it doesn't just go to waste >.<

    If you really only want backups of the current contents, don't use Time Machine.
    It's designed to keep copies of things you've changed or deleted for as long as possible. This allows you an excellent chance to recover a previous version of something you changed or deleted in error.
    It also allows you to revert your entire system to the exact state it was in at the time of any previous backup, even if that's a different version of OSX. It's rare, but if an OSX update, or installation of a kernel extension or 3rd-party app makes a huge mess, it's much easier and more reliable than rebuilding everything.
    You might want to review the [Time Machine Tutorial|http://www.apple.com/findouthow/mac/#timemachinebasics] and perhaps browse [Time Machine - Frequently Asked Questions|http://web.me.com/pondini/Time_Machine/FAQ.html] (or use the link in *User Tips* at the top of this forum). See #1 there for size considerations.
    For alternatives, see Kappy's post on [Basic Backup|http://discussions.apple.com/thread.jspa?messageID=12366915#12366915].

Maybe you are looking for