ServerSocket skrews everything up

I have created a server socket that runs in a separate thread that is a subclass of Thread. When the server socket is created, there are a bunch of problems that occur after it that seem unrelated: In the "main" thread, I try to add an ActionListener to a button after creating the server socket, but the runtime complains that there is no class definition of something. Also, this code does not work after the server socket is created (It throws the exception):
try {ipAddressString = InetAddress.getLocalHost().getHostAddress();}
catch (java.net.UnknownHostException e) {System.out.println(ipAddressString);}
The problem is the server socket because when the server socket is not created in the thread, then there are no problems. This is very strange. What do I do?

What is the exact exception you get and if possible paste the code.

Similar Messages

  • ServerSocket accept method is not working...

    ServerSocket provider = new ServerSocket(10000);
    Socket clientSocket = provider .accept();
    In my application accept() has some problem and unable to return Socket instance.Can anyone tell me and suggest some idea.
    Regards,
    Pradeep

    pradeep_dubey wrote:
    ServerSocket provider = new ServerSocket(10000);
    Socket clientSocket = provider .accept();
    In my application accept() has some problem and unable to return Socket instance.No, accept works just fine and is able to return a Socket instance.
    Can anyone tell me and suggest some idea.*** Make sure you're using accept() correctly.
    *** Make sure you're properly interpreting what you're observing before drawing the conclusion "unable to return Socket instance."
    *** Make sure no other process is already listening on that port. (Probably would manifest before you even called accept(), but not having seen your code, test procedures, or thought process, I figured I'd throw it out there.)
    *** Make sure you have permission to open the port on which you're trying to listen. (Probably would manifest before you even called accept(), but not having seen your code, test procedures, or thought process, I figured I'd throw it out there.)
    *** Make sure you're not smothering any exceptions that might be occurring prior to accept() and then going on as if everything were fine.
    *** Provide an SSCCE that shows exactly what you're doing, and describe exactly what is going wrong. "Doesn't work" contains no information.

  • Construction of a new ServerSocket taking abnormally long - ipv6-related

    SUMMARY
    It takes 180+ seconds to open a ServerSocket if IPv6 is present on the loopback device.
    SYSTEM
    Debian unstable
    Linux desktop3.mgn 2.4.27-speakup #1 Fri Feb 25 15:43:38 EST 2005 i686 GNU/Linux
    java version "1.4.2_06"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_06-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_06-b03, mixed mode)
    MORE INFO
    Last place within PlainSocketImpl everything's alright is     /**
         * Load net library into runtime.
        static {
         java.security.AccessController.doPrivileged(
                new sun.security.action.LoadLibraryAction("net"));
         initProto();
        }After the call to initProto (which is a native method) it takes 180+ seconds for the last connect() call below (got i from running strace) to timeout:socket(PF_INET6, SOCK_STREAM, IPPROTO_IP) = 5
    listen(5, 1)                            = 0
    getsockname(5, {sa_family=AF_INET6, sin6_port=htons(37753), inet_pton(AF_INET6, "::", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=0}, [28]) = 0
    socket(PF_INET6, SOCK_STREAM, IPPROTO_IP) = 6
    connect(6, {sa_family=AF_INET6, sin6_port=htons(37753), inet_pton(AF_INET6, "::1", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=3221214872}, 24) = -1 ETIMEDOUT (Connection timed out)TEST PROGRAMimport java.net.*;
    public class Test {
         public static void main(String[] args) {
              try {
                   long start = System.currentTimeMillis();
                   ServerSocket serverSocket = new ServerSocket(4445);  // <-- this is what takes abnormally long
                   long stop = System.currentTimeMillis();
                   System.out.println("stop - start = " + (stop - start));
              } catch (UnknownHostException e) {
                   e.printStackTrace();
                   System.exit(-1);
              } catch (java.io.IOException e) {
                   e.printStackTrace();
                   System.exit(-2);
    }CASE "ON"# ip a show dev lo
    1: lo: <LOOPBACK,UP> mtu 16436 qdisc noqueue
        link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
        inet 127.0.0.1/8 scope host lo
        inet6 ::1/128 scope host
    $ java Test
    stop - start = 189011CASE "OFF"# ip a del ::1/128 dev lo
    # ip a show dev lo
    1: lo: <LOOPBACK,UP> mtu 16436 qdisc noqueue
        link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
        inet 127.0.0.1/8 scope host lo
    $ java Test
    stop - start = 18Commands executed to "turn ipv6 on/off":ip a del ::1/128 dev lo
    ip a add ::1/128 dev loNo other programs show this delay. Is this a bug?

    I think so, I've read something like that in BugParade.
    Try Java5 or Java6 (Mustang) with your code.
    --Marc                                                                                                                                                                                                                           

  • ServerSocket with multiple NIC

    I need? (want!) to write a server type application that will listen to requests that arrive via 2 (or more) NICs.
    My problem is that the program seems to ignore the second card.
    OK some code...
    waiter1= new Waiter("123.456.789.12");
    waiter1.start();
    waiter2= new Waiter("234.567.890.123");
    waiter2.start();
    class Waiter extends Thread{
    private String IPaddress;
    public Waiter(String IPAddress){
    this.IPAddress=IPAddress;
    public void run(){
    System.out.println((NetworkInterface.getByInetAddress(InetAddress.getByName(IPAddress)).getName())
    ServerSocket sSocket=new ServerSocket(1234,0,InetAddress.getByName(IPAddress));
    while(forever){
    Cover cover=new Cover(sSock.accept());
    cover.start();
    class Cover extends Thread{
    private Socket sock;
    public Cover(Socket sock){
    this.sock=sock;
    public void run(){
    // do all the usefull stuff
    it gives the right system output, ie..
    eth0
    eth1
    requests are handled ok on the first IP addy, but not on the second.
    Ive seen a bug report relating to MultiCast sockets (seems like the argument is ongoing), but nothing about ServerSockets
    btw the code is a transcript, working version compile s and runs :-)

    Well.. if you want to listen to anything on any nic you could just start a ServerSocket on a port only...
    is there anything else listening on the second IP at port 1234? or whichever port you're using?
    put try / catch / e.printStackTrace() around where you're creating the serversocket so you can see if the socket is actually available..
    if you don't like the first approach, the accept() method of a single serverSocket can be "listened" to by as many threads as you want... so you can still have it multithreaded
    ah and the address "0.0.0.0" essentially means all available IP's ... so if you create a serversocket on "0.0.0.0" port 80 you'll recieve everything going to port 80

  • ServerSocket  -Error #2004 but only after install air app in win XP

    OOPS wrong section, posted also in Adobe AIR2....sorry
    When i try to connect i receive: Error #2004 after bind().
    but only when start the installed air on win XP,
    testing in flash CS4 is ok and on macOS 10.6 is always ok
    here' the code:
    import flash.net.*;
    import flash.net.ServerSocket;
    import flash.events.ServerSocketConnectEvent;
    import flash.errors.*;
    var servSok:ServerSocket = new ServerSocket();
    servSok.addEventListener(Event.CONNECT, connect);
    var msg:TextField = new TextField();
    msg.height=300;
    msg.width=300;
    msg.x=50;
    msg.y=50;
    this.addChild(msg);
    msg.appendText("------MSG--------\n");
    function connetti(e:Event):void {
        try {
            var port:int = int(8888);
            var address:String = "0.0.0.0";
            this.servSok.bind(int(port),String(address));
        } catch (e:Error) {
            this.msg.appendText("errore bind:"+e.message+"\n");
        try {
            this.servSok.listen(5);
        } catch (e:Error) {
            this.msg.appendText("errore listen:"+e.message+"\n");
            trace("errore listen:"+e.message);
    function connect(e:ServerSocketConnectEvent):void {
        msg.appendText("connesso:"+e+"\n");
    //----conn is a button....
    this.conn.addEventListener(MouseEvent.CLICK,connetti);
    stop();
    Can anyone may help me?

    Well, well, well, right before somenone could answer me. I found the answer just here in the forum. I really love it!!!
      Seems to be a incompatibility with the file created on Folder Lock installation: "windrvnt.sys." In this case, it is just uninstall Folder Lock and tah dah! Everything works perfectly.
      Here comes my request: Hey, developers you all could give a try in resolve this issue, huh? At least give a try...It'll be very nice have the two programs properly installed in anybody's (who wants it) system.
      Thanks, anyway for this space to research, change some infos even undirectly. If it was not this forum and all the debate in here maybe I'll be in the dark search for the resolution of it.
      Thanks.

  • ServerSocket connection reset under weird circumstances

    Hi all,
    I'm trying to write a very simple TCP/IP server, to provide XML data to a web browser. This should be dead easy, but I'm encountering something weird. I hope you can help me.
    I can successfully create a ServerSocket on a given port, and accept connections. The problem arises when I try to send data to the client. I obtain the OutputStream from the Socket, write some bytes to it, flush, and close.
    Oddly enough, my web browser usually (but not always) tells me that the server reset the connection while the page was loading. I played around with the code, and discovered that if I make the thread sleep before closing the output stream, everything works fine. It's almost as though the data is being put on the stream, and I'm closing the stream in the middle of the transfer. Weirder still, if I send a really large string to the client, the problem disappears.
    Has anyone else encountered this problem? How did you resolve it? Is there any way of monitoring the transfer, so that the connection is closed only when it has finished?
    Below is some code that demonstrates the problem. If you leave the string length as small, and leave the thread sleep code commented out, the problem should appear. If you reinstate the sleep code, or increase the string length to 10000 or more, the problem should disappear.
    The client web browser connects at: http://127.0.0.1:5555
    Thank you very much, in advance!
    public class ServerThread
       public static void main( String[] aArgs )
          // Build a string of variable length.
          // NOTE:  If the string length is small, the problem appears
          //        and must be addressed by sleeping the thread.
          //        If the string length is large (>10000), no sleeping
          //        is necessary.
          // The string length
          int lStringLength = 10;
          // Build a long nonsense XML string
          StringBuilder lBuilder = new StringBuilder();
          lBuilder.append( "<data>\n" );
          for ( int i = 0; i < lStringLength; i++ ) {
             lBuilder.append( "   <data_point>Testing" )
                .append( i )
                .append( "</data_point>\n" );
          lBuilder.append( "</data>" );
          // The server.
          try {
             // Initialize a server socket
             ServerSocket lServerSocket = new ServerSocket( 5555 );
             // Iterate indefinitely
             while ( true ) {
                // Listen for a connection to this socket, and accept
                Socket lSocket = lServerSocket.accept();
                // Get the socket output stream
                OutputStream lOutputStream = lSocket.getOutputStream();
                // Write the data to the output stream
                lOutputStream.write( lBuilder.toString().getBytes() );
                // Flush the output stream
                lOutputStream.flush();
                // Sleep for awhile
                // NOTE:  If the thread closes the output stream immediately,
                //        the client doesn't receive the data!!
                try {
                   Thread.sleep( 1000 );
                } catch (InterruptedException ex) {
                   ex.printStackTrace();
                   return;
                // Close the output stream and socket
                lOutputStream.close();
                lSocket.close();
          } catch (IOException e) {
             e.printStackTrace();
             return;
    }

    Interesting...that makes sense. Do you know of an easy way to tell when the request has been entirely received, other than to read from the input stream in a loop? Is there a better way than this, for example:
    InputStream lInputStream = lSocket.getInputStream();
    BufferedReader lReader = new BufferedReader( new InputStreamReader( lInputStream ) );
    String lStr;
    while ( ( lStr = lReader.readLine() ) != null && ( lStr.trim().length() > 0 ) )
       ;

  • I can't listen on a ServerSocket! Any help?

    Hi,
    I'm trying to write an applet that can talk to another applet over the internet. I create a line like this...
    serverListen = new ServerSocket(1555);
    so I'm listening on port 1555, but since I am doing this over the internet and not on a network, do I still have to worry about ports?
    My problem is that everytime I run into the try/catch statement, I always get the catch statement and I can never open a socket. I have uploaded the applet and everything else I need onto anglefire.com (a free hosting service) and I still get the error.
    Any advice?
    thanks

    I would suspect you're running into Applet security issues although you're not giving much to go on here.

  • ServerSocket as a thread

    Hi, i have made a class, SockServ, which extends Thread, in this class i create a ServerSocket an then wait for connecting clients and create worker threads acordingly.
    Now, when i want to close down everything, i start by going through all the worker threads and interrupt them which all goes fine but when i try to interrupt SockServ i dont get a interrupt exception.
    Here is how i create the SockServ class:
    SockServ scks= new SockServ();
    Thread t = new Thread(sockServThreadGroup,scks);
    t.start();
    t.setName("SocketServ");And here is the run method of the SockServ class:
    public void run()
          while(running)
            try
                Socket socket = servSock.accept();
                Thread t1 = new Thread(myThreadGroup,new SocketServerService(socket,s,tempTable),s);
            catch (InterruptedException e)
             System.out.println("SocketServer interrupted");
               running=false;
    }Thank you.

    Try explicitly closing the socket.In my ServSock class i create my worker threads too and assign them to a new thread group, but the ServSock class is a thread as well and it is assigned to a threadgroup as well. Could it have something to do wit that?
    when i run this i get a nullpointer exception but activecount() is not 0
    for (int i = 0; i < sockServThreadGroup.activeCount(); i++)
                System.out.println("active SocetServer Threads: "+sockServThreadGroup.activeCount());
               sockServListThreads.interrupt();

  • Why does ServerSocket stop working after some time?

    Hi to all.
    I have a following problem:
    I wrote a multithread application that uses sockets ( TCP ), and use it to transfer some objects between computers in VPN.
    It all works just fine, except that sometimes my server socket ( implemented as a separate Thread ) just stops working, and other computers cannot connect to it...?
    I didn't specify setSOTimeout(), and did all Exception catch-ing in the thread.
    Today, I had some >50000 connections in about 5 hours, and than it just stopped! My server socket stopped accepting any connections...
    I restarted my application, and everything worked again properly...
    Does anybody know why is this happening?
    Please, any suggestion is appreciated....
    Thank you.

    Hi, thank you all for answering me.
    @baftos:
    I didn't specify any backlog parameter value. 50 connections at a time seems more than enough for this application... ( Are you sure that 50 is the default value )
    I never have more than about 40 connections simultaneously opened, and yes - each one is a separate thread.
    @dannyyates:
    You're rights, I should have provided some code.
    Here it is:
    public class Server implements Runnable
    ServerSocket serversocket = null;
    Socket clientSocket = null;
    continueWorking boolean = true;
        public void run()
                startServer(); 
        public void startServer()
            try
                 serversocket = new ServerSocket(3344);
            catch (IOException e)
                 System.out.println(e.getMessage());  
         while ( continueWorking==true )
             try
                  clientSocket = serversocket.accept();
                  Worker Worker = new Worker(clientSocket);
                  new Thread(Worker).start();
             catch (IOException e)
                  System.out.println(e.getMessage());
            System.out.println("The server is shutting down...");
    class Worker implements Runnable
        ObjectInputStream obj;
        Socket clientSocket;
        public Worker(Socket clientSocket)
             this.clientSocket = clientSocket;
            try
              obj = new ObjectInputStream(clientSocket.getInputStream());
             catch (IOException e)
                  System.out.println(e.getMessage());
        public void run()
            Object object;
         try {
                          try
                               object=(Object)obj.readObject();
                                                   // do something with object....
                          catch (ClassNotFoundException e)
                               System.out.println(e.getMessage());
                        catch (Exception e)
                obj.close();
                clientSocket.close();
         catch (IOException e)
        catch (Exception e)
        }What I don't like here is the constructor of the Worker. Could this block the server?
    Edited by: Darko on Apr 7, 2009 11:24 PM

  • I have a problem with wifi in my iphone 4s, i already try everything and download latest version 7.1(11D167) but wifi switch is not working, its my humble request to Apple support team that pls resolve this problem as soon as possible because

    I have a problem with wifi in my iphone 4s, i already try everything and download latest version 7.1(11D167) but wifi switch is not working, its my humble request to Apple support team that pls resolve this problem as soon as possible because its a prestiage of Apple Company.
    Pls inform me how can i resolve the problem of wifi.

    You have to go to autherized iPhone agent.

  • Hello I am experiencing some problems for my iMessage and FaceTime. I did the steps the Apple provided online and I still can't get it to work. My updates are up to date. Everything is working fine it's just that the Apple iMessage won't except anyth

    hello I'm experiencing some problems with my iMessage and face time. I did with Apple provided me online. I did the steps. Nothing will work, it keeps saying activation turn on Wi-Fi when my Wi-Fi is turned on. As soon as I got this on Christmas. iMessage and FaceTime have not been working. My Apple and ID password are correct. Everything else is working fine. My iOS updates are up to date, everything is fine except FaceTime and iMessage

    Did you try everything here?
    iOS: Troubleshooting Messages
    Using FaceTime and iMessage behind a firewall
    iOS: Troubleshooting FaceTime and iMessage activation
    FaceTime, Game Center, Messages: Troubleshooting sign in issues
    In the future saying your tried the Apple on-line articles does provide us with information as to which ones you found and tried

  • Hi Guys,  I am using the full width video widget on a site. The widget was working perfectly however I have just added additional content to the site and re-uploaded and now the video is not working! Please help I have tried everything and am freaking out

    Hi Guys,
    I am using the full width video widget on a site. The widget was working perfectly however I have just added additional content to the site and re-uploaded and now the video is not working! Please help I have tried everything and am freaking out as this web-site has been payed for by my client.
    Alex

    Many thanks.
    With those symptoms, I'd try the following document:
    Apple software on Windows: May see performance issues and blank iTunes Store
    (If there's a SpeedBit LSP showing up in Autoruns, it's usually best to just uninstall your SpeedBit Video Accelerator.)

  • Firefox update 10 won't open and the previous version 3.6 won't load any pages. I have done everything this site said to do. HELP?

    The last version of Firefox that I had was the one before 3.6. I stopped upgrading due to it always messing up and not working right for me... whether it be due to vista, or just errors on your part. My husband decided to upgrade firefox to the newest one two days ago because the version I had was just "too slow!" Ever since he did that, I cannot get firefox to open. No matter how many times I uninstall it and delete everything mozilla on my computer then reinstall after restarting my computer, it just refuses to open. Every time i try it says that firefox has stopped working. It cant even check for solutions. I then try to click on the icon and I get something that says: firefox.exe - Bad Image C:\Windows\WinSxS\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.6195_none_d09154e044272b9a\MSVCP80.dll is either not designed to run n windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support.
    I have tried installing it over and over again several times, same message shows up. So i had clicked on the link to go download the previous version of firefox... what sucks is that the only version on the site is 3.6.27. I have never upgraded to this. So the second i installed that version, i now am able to open up firefox... BUT it is unable to connect. I have internet... a pretty bad ass connection. So my internet is not the problem. I then looked up how to fix that issue and did all 5 things listed under the Firefox cant load pages but other browsers can link. Still nada! I am now stuck using IE and going insane. I am on the verge of throwing my laptop out of the damn window because I have to wait 3 hours for google to load. Nothing is working for me... and it would be appreciated for something more. If i can get help with a ton of details on what to do or how to fix this issue... either version... i would greatly appreciate it. I am going nuts having to put up with IE because my husband decided to update Firefox to a version that sucks with vista!

    Here is the system requirements page: http://www.mozilla.com/en-US/firefox/system-requirements.html.
    http://www.mozilla.com/en-US/firefox/all-older has the latest 3.6.x version, and http://www.floodgap.com/software/tenfourfox/ is another option.

  • Why does my safari browser frequently gives me a gray screen? I resetted my safari many times and it doesn't help. Also sometimes when I scroll it gives me this weird scrolling effect where everything is either upside or messed up.

    Why does my safari browser frequently gives me a gray screen? I resetted my safari many times and it doesn't help. Also sometimes when I scroll it gives me this weird scrolling effect where everything is either upside or messed up.

    This article is for startup but it might help.  http://support.apple.com/kb/ts2570

  • My iMac 8.1 was slowing down and had permissions problems. I backed everything up, and then re-installed. Now all I get is a black screen. Power+D gives me a hardware error message: HDD-1336. Help!

    My iMac 8.1 (10.6.8 ) was slowing down and had recurrent permissions problems, mostly with Java. I backed everything up, and then re-installed from time machine. Now all I get is a black screen which says I need to reboot. Power+D gives me a hardware error message: 4 MOT/1/40000003: HDD-1336 or HDD-1327. When I reboot from the OSX CD and start disc utilities everything checks out OK. When I reload 10.5.2 from the OSX CD everything seems to work OK and no more permissions problems. But then I loose all my email and safari stuff. Anyone have any ideas short of going back to my old PC?

    DonM. wrote:
    Hi
    Thanks for the help. No point in fooling around with it any more. Will I be able to use it as a monitor if I get a mimi mac?
    Cheers. Don
    No unfortunatley it's too old, you are referring to Target Display Mode which became avialble in 2009, your 2008 needs to have the HD replaced. I'd still do that if everything else is OK or you can simply buy a new MM and display or even a new iMac  or an Apple refurbished iMac to save money.

Maybe you are looking for