Thread Gui Socket Challange

The problem is when i start the thread form the MAIN class, the connection is ok but when i try to update the GUI the update does not come true.
The System does not update the component i like to add tru the following methode.
Why does the system not update and how can i make it work.
computerview.setComputer("Izzy",new ComputerControl());
import javax.swing.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.awt.event.ActionEvent;
public class Server extends Thread{
        JButton addComp = new JButton();
        String inputLine;
        ComputerView computerview = new ComputerView();
    public void startServer() throws IOException {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        out.println("Hello Client");
        while ((inputLine = in.readLine()) != null) {
             String state = "WAITING";
            System.out.println(state);
            if(state.equals("WAITING")){
                if (inputLine.equals("ID")){
                   System.out.println("Client :"+inputLine );
                      out.println("Who are you?");
                      state = "WAITINGFORID";
                      System.out.println(state);
            if(state.equals("WAITINGFORID")){
                      computerview.setComputer("Izzy",new ComputerControl());
                      out.println("You are now Registred!");
                      state = "WAITING";
                      System.out.println(state);
    public void run(){
         try {
            startServer();
        } catch (IOException e) {
            System.err.println(e);
}

As a general rule all GUI components should be updated from the event thread thread which means you may need to use the SwingUtilities.invokeLater(...) method to do the updates. This thread give a simple example:
http://forum.java.sun.com/thread.jsp?forum=57&thread=437592

Similar Messages

  • Using Threads And Sockets

    Hello,
    I want to create a program that can send 2 or more files through the socket to the same client at the same time. Is it possible? I am trying to use threads to do this but I am not sure what to do in those threads. Should I send the socket to the thread class and create BufferedReader and DataOutputStream again in the thread?
    Also should I create threads in the client-side?
    Thanks
    Edited by: bcaputcu on May 18, 2010 2:19 AM

    bcaputcu wrote:
    Hello,
    I want to create a program that can send 2 or more files through the socket to the same client at the same time. Is it possible?No. At least not in the way you're thinking.
    I am trying to use threads to do this but I am not sure what to do in those threads. Should I send the socket to the thread class and create BufferedReader and DataOutputStream again in the thread?No, because you can't do that. The socket won't create multiple streams for your threads.
    Also should I create threads in the client-side?No.
    You need to send the files one at a time. While you could basically send the data interleaved, it would still only involve only one thread, one socket and one set of streams. And it would be a silly thing to do.

  • Threads as Socket Readers

    What does mean by Socket Readers?
    How it improves the performance of Application by configuring percentage of threads as socket readers?
    Can someone please answer my questions?

    Hi Achhi,
    Socket Reader Threads are the Threads which are responsible for reading the incoming request data. We can divide the Socket reader threads in two categories:
    Pure Java Socket Reqders: The pure-Java socket reader implementation, where the socket reader threads continually poll all opened sockets to determine whether they contain data to be read, even if the sockets have no data to read. (From Performance Point This is Not Good that the Sockets will be in Opened Mode even if there is no Data to read)
    Native Socket Readers: (These are the Dafault Socket Readers) The native IP socket reader provided by the host machine's operating system, where the socket reader threads target only active sockets that contain data to be read. Native socket readers never poll sockets because they are immediately notified when a socket needs to be serviced. For Better Performance You should always prefer using Native Socket Readers.
    To Enable Native Socket Readers You can Login to AdminConsole--->Servers ---><SERVER_NAME>--->configuration (Tab)--->Tuning (SubTab)---> "Enable Native IO" (This checkbox must be checked)
    Still If you want to use the Java Socket Readers .... still you can improve the performance of socket communication by configuring the proper number of socket reader threads for each server instance. For best performance, the number of socket reader threads in WebLogic Server should equal the potential maximum number of opened sockets.
    Thanks
    Jay SenSharma
    http://weblogic-wonders.com/weblogic (WebLogic Wonders Are here)

  • I need to multiplex communication between threads and sockets

    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

    Marzullo wrote:
    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?For small apps like that, I've found it helpful to have two threads per socket: 1 reader and 1 writer. The reader can block on read() 99% of the time, while the writer is blocked on LinkedBlockingQueue.take() 99% of the time (or Object.wait() depending). The writer's queue is populated from the outside with whatever messages are destined to that socket.
    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?If thread1 is blocked on read() then it will receive any data that was sent to it, there's no need to wake it up because it gets what it's been waiting for (data on the input stream). Thread7 just needs to write data to the socket's output stream and the other end wakes up automatically because read() only blocks until data is available.

  • This is very important... It concerns topics of threads and sockets...

    Hey...
    This has been very complicating for me.
    I have tried so many solutions for the past
    few days but i have been stuck here with no
    no things to think of. I would really appreciate if someone
    can help me out in doing this or any suggestions.
    Now this is the case..
    My program runs a frame with an "OPEN" menuitem
    a connect button ,upload button, a porgress bar and a progress text label near it.... In the open u choose a file that u want to upload. In the connect u choose the IP address that u need to Upload the chosen file to. And in the upload, u start uploading u're file. Now i am using sockets to connect through my machine and the chosen IP address. The progress bar should note the process of uploading and accordingly get's updated...The progress text label should either say "No String" or "Uploading" when i'm uploading as well as blinking on and off....
    Now i got through almost all of the stuff above, i'm only stuck in updating the progress bar and the text. To make things more clearer i will include the upgrade method that i do the connection and start sending the stuff. In there i've also created a thread to update the bar but for now, i only set the value to 10.... The thing is it never updates the bar unless the whole process of downloading is done. The file chosen to be uploaded is about 1MG and it takes about 40secs to send the whole file to another machine.....
    I've also tried using seperate threads in different classes
    but it never worked..
    NOW THE PROGRESS BAR HAS BEEN DECLARED IN THE
    PROGRAM AS JProgressBar. What i'm suppose to do is
    read the file in 29 bytes. Then send 15 and then 14.
    Once i'm less than 29 bytes i send either 15 or 14 or
    the remainder... The sendMsg method is the one that
    handles sending the bytes and receiving the
    acknowledgment. The socket is created when i hit the
    connect button and choose the IP address...
    Please any extra suggestion is appreciated.
    /CODE/
    public void UpgradeActionPerformed(ActionEvent e)
    final Runnable doprogressValue = new Runnable()
    public void run()
    jProgressBar.setValue(10);
    Thread appThread = new Thread()
    public void run()
    try
    SwingUtilities.invokeAndWait(doprogressValue);
    catch (Exception ex)
    ex.printStackTrace();
    try
    DataInputStream inputStream = new DataInputStream(new FileInputStream(fileName));
    //Send Set to DownLoad Moad message
    byte[] msg = new byte[MaxMessageSize];
    msg[0]=(byte)((SystemSpecific<<4) | (DataCounter));
    msg[1]=FirmWareDNLMode;
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Set Progress Bar Max & Min values
    jProgressBar.setMinimum(0);
    jProgressBar.setMaximum(inputStream.available());
    while((inputStream.available()) >= MaxMessageRead)
    bytesRead = inputStream.read(mainBuffer,offset,MaxMessageRead);
    //Send First 15 Bytes
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Send Next 14 Bytes
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Send The 15 Bytes Left
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Send The 14 Bytes Left
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Send The Remainder Bytes
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Send Set to Reset Mode
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    inputStream.close();
    socket.close();
    connectionStatus.setText("Not Connected");
    fileStatus.setText("Loading completed");
    upgradeButton.setEnabled(false);
    connectButton.setEnabled(false);
    catch(NullPointerException null_ex)
    JOptionPane.showMessageDialog(null,"Connection Not Created","Error",JOptionPane.ERROR_MESSAGE);
    catch(IOException IO_ex)
    IO_ex.printStackTrace();
    appThread.start();
    /CODE/

    Yeah... i dide finally figure out a way doing it.... This is how i did it....
    /CODE/
    // This is all going to be under the upload action...
    {//beggining of the uplaod action
    finally Runnable doProgressVal = new Runnable()
    public void run()
    time.start();//This is an instance of class timer that i
    // created. It actually sets the value of
    // of the progressBar to the latest upload
    Thread mainThread = new Thread()
    public void run()
    SwingUtilities.invokeAndWait(doprogressVal);
    do the uploading of the file to the specified server
    mainThread.start
    }//end of upload action
    /CODE/
    Hope this help if u want it for something. It works fine..

  • Identifying Execute Queue Threads as Socket Readers

    Hi All,
    Preface: I am trying to identify at any given instance the percentage of
    socket reader threads that are in use - this will help me to identify when
    all threads are in use and unable to service user requests. Thus my goal is
    to identify threads that are socket readers and whether they are active or
    idle.
    Through JMX I can obtain an instance of each
    weblogic.management.runtime.ExecuteThread, which lists the same information
    that you see in the console if you drill down to the thread level, for
    example:
    mydomain> Servers> myserver> Active Execute Queues> default> Execute Threads
    That information includes:
    - thread number
    - total requests
    - last request
    - current request
    - transaction
    - user
    - is the thread idle?
    Now my question is from this information can you identify which of these
    threads are being used as socket readers?
    Here are some excerpts from my JMX calls:
    Name: ExecuteThread: '0' for queue: 'default'
    Execute Queue Runtime Name: default
    Current Request: null
    Last Request: Http Request: /bookstore/en/authors/showauthors.jsp
    User: null
    Is Idle?: true
    Name: ExecuteThread: '15' for queue: 'default'
    Execute Queue Runtime Name:default
    Current Request: null
    Last Request: Scheduled Trigger
    User: null
    Is Idle?: true
    Name: ExecuteThread: '26' for queue: 'default'
    Execute Queue Runtime Name:default
    Current Request: null
    Last Request: ListenRequest for a new connection on: 'Socket
    addr=127.0.0.1,port=2061,localport=7001]'
    User: null
    Is Idle?: true
    Name: ExecuteThread: '59' for queue: 'default'
    Execute Queue Runtime Name:default
    Current Request: Socket Reader Request
    Last Request:
    weblogic.transaction.internal.ServerCoordinatorDescriptor$2@138786
    User: null
    Is Idle?: false
    It would appear that the "ListenRequest" last request would identify a
    socket reader, only I have 60 threads in my default execute queue with 70%
    dedicated to socket readers and the number of threads that say their last
    request was "ListenRequest ..." is only 5.. Furthermore there is only one
    "Socket Reader Request" identified thread.
    Are threads identified as socket readers permanently or constantly reused
    for whatever purpose is required (with a cap of use based off of the socket
    reader perspective)?
    Thanks in advance for your help!
    Steve

    Hi Achhi,
    Socket Reader Threads are the Threads which are responsible for reading the incoming request data. We can divide the Socket reader threads in two categories:
    Pure Java Socket Reqders: The pure-Java socket reader implementation, where the socket reader threads continually poll all opened sockets to determine whether they contain data to be read, even if the sockets have no data to read. (From Performance Point This is Not Good that the Sockets will be in Opened Mode even if there is no Data to read)
    Native Socket Readers: (These are the Dafault Socket Readers) The native IP socket reader provided by the host machine's operating system, where the socket reader threads target only active sockets that contain data to be read. Native socket readers never poll sockets because they are immediately notified when a socket needs to be serviced. For Better Performance You should always prefer using Native Socket Readers.
    To Enable Native Socket Readers You can Login to AdminConsole--->Servers ---><SERVER_NAME>--->configuration (Tab)--->Tuning (SubTab)---> "Enable Native IO" (This checkbox must be checked)
    Still If you want to use the Java Socket Readers .... still you can improve the performance of socket communication by configuring the proper number of socket reader threads for each server instance. For best performance, the number of socket reader threads in WebLogic Server should equal the potential maximum number of opened sockets.
    Thanks
    Jay SenSharma
    http://weblogic-wonders.com/weblogic (WebLogic Wonders Are here)

  • Identifying Execute Threads as Socket Readers

    Hi All,
    Preface: I am trying to identify at any given instance the percentage of
    socket reader threads that are in use - this will help me to identify when
    all threads are in use and unable to service user requests. Thus my goal is
    to identify threads that are socket readers and whether they are active or
    idle.
    Through JMX I can obtain an instance of each
    weblogic.management.runtime.ExecuteThread, which lists the same information
    that you see in the console if you drill down to the thread level, for
    example:
    mydomain> Servers> myserver> Active Execute Queues> default> Execute Threads
    That information includes:
    - thread number
    - total requests
    - last request
    - current request
    - transaction
    - user
    - is the thread idle?
    Now my question is from this information can you identify which of these
    threads are being used as socket readers?
    Here are some excerpts from my JMX calls:
    Name: ExecuteThread: '0' for queue: 'default'
    Execute Queue Runtime Name: default
    Current Request: null
    Last Request: Http Request: /bookstore/en/authors/showauthors.jsp
    User: null
    Is Idle?: true
    Name: ExecuteThread: '15' for queue: 'default'
    Execute Queue Runtime Name:default
    Current Request: null
    Last Request: Scheduled Trigger
    User: null
    Is Idle?: true
    Name: ExecuteThread: '26' for queue: 'default'
    Execute Queue Runtime Name:default
    Current Request: null
    Last Request: ListenRequest for a new connection on: 'Socket
    addr=127.0.0.1,port=2061,localport=7001]'
    User: null
    Is Idle?: true
    Name: ExecuteThread: '59' for queue: 'default'
    Execute Queue Runtime Name:default
    Current Request: Socket Reader Request
    Last Request:
    weblogic.transaction.internal.ServerCoordinatorDescriptor$2@138786
    User: null
    Is Idle?: false
    It would appear that the "ListenRequest" last request would identify a
    socket reader, only I have 60 threads in my default execute queue with 70%
    dedicated to socket readers and the number of threads that say their last
    request was "ListenRequest ..." is only 5.. Furthermore there is only one
    "Socket Reader Request" identified thread.
    Are threads identified as socket readers permanently or constantly reused
    for whatever purpose is required (with a cap of use based off of the socket
    reader perspective)?
    Thanks in advance for your help!
    Steve

    Hi Achhi,
    Socket Reader Threads are the Threads which are responsible for reading the incoming request data. We can divide the Socket reader threads in two categories:
    Pure Java Socket Reqders: The pure-Java socket reader implementation, where the socket reader threads continually poll all opened sockets to determine whether they contain data to be read, even if the sockets have no data to read. (From Performance Point This is Not Good that the Sockets will be in Opened Mode even if there is no Data to read)
    Native Socket Readers: (These are the Dafault Socket Readers) The native IP socket reader provided by the host machine's operating system, where the socket reader threads target only active sockets that contain data to be read. Native socket readers never poll sockets because they are immediately notified when a socket needs to be serviced. For Better Performance You should always prefer using Native Socket Readers.
    To Enable Native Socket Readers You can Login to AdminConsole--->Servers ---><SERVER_NAME>--->configuration (Tab)--->Tuning (SubTab)---> "Enable Native IO" (This checkbox must be checked)
    Still If you want to use the Java Socket Readers .... still you can improve the performance of socket communication by configuring the proper number of socket reader threads for each server instance. For best performance, the number of socket reader threads in WebLogic Server should equal the potential maximum number of opened sockets.
    Thanks
    Jay SenSharma
    http://weblogic-wonders.com/weblogic (WebLogic Wonders Are here)

  • Using thread and socket connection with other machines

    Hi all!
    we are using weblgoic 5.1 SP9 JDK1.2.2
    we already using java.net.Socket and java.lang.Thread
    to communication TANDEM Machine on the weblogic.
    the reason why we use to socket and thread even though it is not
    recommanded is that below
    1. once we connect Socket, then we using until server shutdown or
    connection may has the problem, so we're using thread to wait
    java.io.Inputstream to read from socket.(if I using EJB, It can't
    wait socket inputstream indefinetly, because it has timeout)
    2. we're logging Database date sent or received with TANDEM Machine.
    so we need Database Access. so we using Database Access
    thru Weblogic.
    3. EJB Application using (other EJB Application - send Module)
    to send data to TANDEM Machine. So "Send Module" should
    be implemented EJB.
    but. Now I see there might be problem this framework.
    so, is there some way by just using J2EE spec, to implement this kind of
    framework.
    wait for your great help !!
    regards.

    Yes i've tried interrupt method and it doesn't have any effects on the thread... it stay in connect() method...
    And for the timeouts, in fact i use an API : J2SSH, to connect with SSH protocol, and the setting of connection timeouts is not implemented yet... and the default timeout is about 4 minutes...
    so i don't know how to solve this problem...

  • T Box: help with coaxial vs threaded wall socket issue

    Hi there! Hope someone out there can help me or point me in the right direction! I purchased a T Box Entertainer Bundle for my new rental residence, and after moving in yesterday I received my T Box today. All excited about plugging in the T Box and catching up on some viewing from the past few days, but it seems that while my new place has a TV connection, it is not the standard coaxial type! Arrrggghhhh! There is the usual phone connection attached to the wall, and beneath that a wall plate branded with Telstra (upside down!) and instead of the usual coaxial connection there is a threaded socket with a small female pin port. Just to satisfy my own curiosity I did try and plug the coaxial cable which came with the T Box to the socket, but obviously it doesn't fit either with male or female connections. A bit of slow online searching later (I also don't have my internet or landline connected as yet, and am in a mobile blackspot to compound the problem) and I am pretty sure what I have in the wall is actually a cable or Foxtel connection. From what I've read, if I get an adapter I will still need to get the whole thing rewired to an antenna...is this correct? Or is it possible that as the T Box has Foxtel anyway that either an adapter or a different cable would work?Or is this something that the tech can do when they come out to connect my landline and ADSL2+? Fingers crossed there is a reasonable solution to this as with being in a rental my options are limited!Many thanks in advance to you all.

    AlanM52 wrote:
    That wall plate is for Foxtel – not FTA. You will not be able to get BigPond cable in that complex. DIY I would look at smaller caravan type antenna (window/balcony) and some cable. Not long ago ALDI were selling “active” indoor antennas for about $30-40 bucks, if you can get one and no-go just return.Thanks Alan...but if that is the case, why doesn't Foxtel have any history over the past 6 years of anyone ever having Foxtel in this unit? The wall plate is not Foxtel branded, but Telstra branded. The complex is probably 50 years old, but the reno is a lot more recent - say, a couple of years maximum. Also, Foxtel are telling me that only a couple of people in the last 6 years have ever had Foxtel anywhere in the entire 40-odd apartment complex which is over two separate buildings...why would there be backboned Foxtel cable if no one is using it? Foxtel use Telstra cable to deliver their content - I get that. But if practically no one is using the cable for Foxtel - what ARE they using it for? It doesn't seem to be broadband as I was told only ADSL2+ is available to me...
    There are no visible external antennas, and if all the units have been cabled, why would this one be different? I find it difficult to believe that all the residents are having to rely on rabbit-ears or window antennas simply to get FTA!There are a lot of large metal structures around this area, as well as other frequency-interference objects,so I am surmising that this would be the reason the building has been backboned cabled. But hey - just guessing here... So really - who can I ask about what is actually connected to this address? Foxtel say it's not them and tell me to ask Telstra, Telstra SHOP staff (not the good folk here) are telling me they cant help me in person and I have to call customer service from home,  I don't have a landline or my ADSL connected yet so can only use my mobile for which I have limited service while I wait for the delivery of a 3G home booster thingy. Can anyone tell me to which Telstra department I should be directing my enquiry to?At the moment I have now useless T-Box sitting here begging to be used, which I purchased in good faith on the advice I received from a Telstra provider that I have the necessary and correct connections for it to work! Seeing as they appeared to have access to the information required to check on the service availability to this address and specifically this apartment - who do I need to contact to get more information?At the very least, put me out of my misery - if I have to install an antenna, so be it, but I need to be sure this is the only option available to me before I go through the process of getting landlord, body corporate, aand whoeverelse persmission, not to mention the considerable expense! Please - someone, anyone at Telstra - tell me who I need to contact, to find out once and for all, with absolute certainty what this connection is for!  Sorry if I sound desperate...everyone has been very helpful here so far, but I'm going crazy trying to figure this out!

  • Multi-Threaded gui components and accessor methods

    hello, I'm working on a small gui component which makes use of swingworker to deal with time consuming methods.
    My question is what is the best way to handle accessor methods for example to tackle the following code scenario:
    MyComponent myComponent = new MyComponent();
    myComponent.render(); // long task handed out to a thread
    myComponent.getVariable(); // will only return correct value if render() has completed
    Is the best option to use a Listener and fire a 'render completed' event?
    Thanks for any ideas,
    bm

    I think that's good approach to go with.
    Sai Pullabhotla.

  • Thread - GUI vs Database

    Folks
    I have a performance intensive task within my init method (the database part). I would like to seperate this from the loading of the GUI... therefore I am thinking threads.
    I am vaguely familar with the two thread options that exist. I dont particularly wish to create a specific class for this. Therefore I am thinking towards implementing Runnable option.
    The question is, doing this method I overide the run() method. How do I put the building of the GUI in one thread and the database performance in another...
    Thanks for you help.

    One clarification question: If I implement the code above,
    hence put the database operations in a thread and leave the
    init code untouched would I then be effectively running two
    threads. OR would I need to specifically put the init()
    method AND database operations in TWO seperate threads.Answer: the "main" thread (that you do not explicitly create) will do the init code. The other thread that you do explicitly create, will do the database work. In other words, take your existing init() code, only insert the thread-starting code at the top.
    class YourApplet extends Applet
       public void init()
          // before doing anything else, get the worker going
          DatabaseWorkerThread databaseWorkerThread = new DatabaseWorkerThread();
          databaseWorkerThread.start();
          // get the gui ready
          // here the main thread will do all of the gui work as normal
          // (meanwhile, the other thread is working hard on the database stuff, but
          //  we never know what progress it has made at any point; at end of init,
          //  we don't know whether it is done or not -- or even started for that matter)
       } // end of init method
       class DatabaseWorkerThread extends Thread
          public void run()
             // the database work
       } // end of inner class DatabaseWorkerThread
    } // end of class YourApplet(My choice to extend thread rather than implementing Runnable makes no difference in the reasonable simple case of this short example.)
    /Mel

  • Thread and socket

    Can somebody suggest me some API/program which gives the resources statics of a web/application server? like free listening sockets, memory, threads etc? JRE used is 1.4. My plan is to use this code will run inside a war file and wite it to some log file.

    I'm not sure of a library for it, but at the very least you can execute OS commands such as netstat, top, etc using RunTime and then process the output accordingly. I dont know if that will help in this situation.
    Edited by: ForumKid2 on Jun 2, 2010 12:44 PM

  • Thread with sockets

    Hi,
    I'm trying to implement a thread in the server i am creating which will run when someone connects to it. The problem is, i can't figure out what to put in it. I've tried various things and the program compiles but just aborts when i try to connect to it. Help much appreciated. Here's my code:
    import java.io.*;
    import java.net.*;
    public class sfdb
         private static BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) );               
         public static void main(String[] args)
              ServerSocket Server = null;
              Socket clientSocket = null;
                 String gotdata;
              String sentdata;
                 DataInputStream is;
                 PrintStream os;
              String temport;
              int port = 0;
              System.out.println("Welcome to squarefish server.");
              try
                   System.out.print("Port: ");
                   temport = stdin.readLine();
                   port = Integer.parseInt(temport);
              catch (IOException fred)
                   System.out.println(fred);
              try
                         Server = new ServerSocket(port);
                   System.out.println("Server started...");
                 catch (IOException fred)
                         System.out.println(fred);
              try
                         clientSocket = Server.accept();
                         is = new DataInputStream(clientSocket.getInputStream());
                         os = new PrintStream(clientSocket.getOutputStream());
                   System.out.println("Remote system connected...");
                   os.println("You are now connected to a squarefish database server.");
                   while (true)
                        gotdata = is.readLine();
                                FileReader in = new FileReader(gotdata+".sfdb");
                        BufferedReader br = new BufferedReader(in);
                        String pre;
                        pre = "blah";          
                        while (pre != null)
                             pre = br.readLine();
                             os.println(pre);
              catch (IOException fred)
                         System.out.println(fred);
    }

    I have posted some samples before:
    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Bnoah+%2Bsocket+%2Bgame&col=javaforums&x=35&y=16

  • How do you manually set the # of threads - weblogic.socket.Muxer in 8.1

    We are seeing some strange behavior with an application that has 9 threads as seen in the "Monitor all Active Queues..." I'd like to try to reduce this to 5, where would I set this?
    Thanks!

     Just Google for such things as this: http://www.directron.com/12to7.html
     You can also rig things yourself if you're inclined to do so and have the ability. You can finds instuctions by doing a web search.
     I made something a bit different using a +8V 0.5A voltage regulator just because I had the parts and felt like doing it.

  • Need help with Threading GUI progress bar

    Anyone able to help? I'm sure you've seen this a million times. I've google'd around and tried examples but still can't get a progress bar to work properly under the following situation:
    1. Created a panel with several components to select directory, display directory in tree etc.
    2. When a specific button (Search) is clicked, I want a secondary window to popup and report progress of searching down the directory.
    As you'll probably guess, the progress window isn't being updated until the end. I'm using Threads and using InvokeLater but nothing happens. Is there any good example that does the above? I can't seem to find one to figure this out.
    Thanks
    Speedy.
    Sample code:
    main.java:
    ========
    public class Main {
    public static void main(String[] args) {
    MainPanel mainPanel = new MainPanel();
    mainPanel.show();
    MainPanel.java:
    ============
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class MainPanel extends JFrame implements ActionListener {
    public MainPanel() {
    this.setSize(100,100);
    JButton startButton = new JButton("Start");
    this.getContentPane().add(startButton);
    startButton.addActionListener(this);
    public void actionPerformed(ActionEvent event) {
    ProgressPanel pp = new ProgressPanel();
    pp.show();
    SimpleTask st = new SimpleTask(pp);
    st.start();
    while (st.isAlive()) {
    System.err.println("waiting..");
    try {
    Thread.sleep(100);
    } catch (Exception e) {};
    System.err.println("finished!");
    SimpleTask.java:
    =============
    import javax.swing.SwingUtilities;
    public class SimpleTask extends Thread {
    ProgressPanel pp = null;
    public SimpleTask(ProgressPanel _pp) {
    pp = _pp;
    this.setDaemon(true);
    int i = 0;
    String position = "";
    public void run() {
    Runnable updateGUI = new Runnable() {
    public void run() {
    pp.setText(position);
    try {
    for (i=0; i<50; i++) {
    position = "Now on = " + new Integer(i).toString();
    System.err.println(position);
    SwingUtilities.invokeLater(updateGUI);
    sleep(100);
    } catch (Exception e) {}
    ProgressPanel.java:
    ===============
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class ProgressPanel extends JFrame {
    private JLabel label = new JLabel();
    public ProgressPanel() {
    this.setSize(200,200);
    this.setLocation(100,100);
    this.getContentPane().add(label);
    setText("Start");
    public void setText(String text) {
    label.setText(text);
    }

    Ok, I'll look down that road. I should have said the Thread is being used because the current while loop will be changed to perform real work. Just an example at the moment to show what I'm trying to do. Does this make a difference? The real task will be to drill down directories, counting file types/dirs etc...

Maybe you are looking for