ConnectException thrown when sockets are created at the same time

Hi everyone,
I have written a simple server and a simple client as follows:
SERVER:
import java.net.*;
public class Server
     public static void main(String[] args)
          try
               ServerSocket ss = new ServerSocket(1234);
               while (true)
                    final Socket s = ss.accept();
                    Thread t = new Thread() {
                         public void run() {
                              System.out.println(s.toString());
                    t.start();
          catch (Exception e)
               e.printStackTrace();
CLIENT:
import java.net.*;
public class Client
     public static void main(String[] args)
          try
               int numSocket = 10;
               Socket[] s = new Socket[numSocket];
               for (int i = 0; i < numSocket; i++) {
                    s[i] = new Socket("localhost", 1234);
          catch (Exception e)
               e.printStackTrace();
}When I run the client, the following stack trace was printed after 4 or 5 sockets are created successfully.
java.net.ConnectException: Connection refused
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
        at java.net.Socket.connect(Socket.java:426)
        at java.net.Socket.connect(Socket.java:376)
        at java.net.Socket.<init>(Socket.java:291)
        at java.net.Socket.<init>(Socket.java:119)
        at Client.main(Client.java:12)If I add Thread.sleep(500) after a socket was created, then it's fine. All sockets are created successfullly.
I have tested this on both RedHat linux 7.2 and RHEL 3.0 AS and both fails.
However I run on Windows XP, it's ok even without Thread.sleep
It seems that RH linux cannot handle clients connecting to localhost that quickly. It works well even if I create 100 sockets in a row for WinXP.
I have searched the web for similiar problems, but I couldn't find any.
Please reply if you have the same problem or know how to solve it.
Thanks in advanced!
Joseph

Hello,
Your code is correct and should work, i'm actually quite positive it will work on at least a Windows OS. Also, it is possible you're running into backlog problems but i find it somewhat unlikely that since in most cases the backlog is larger than 10, and you're only testing 10 connections.
Regardless of the actual problem, you seem to be running into issues with a VM implementation that isnt behaving as it should. ServerSocket.accept() is a blocking IO call, and there should be no problem with doing it in a tight loop like yours. It's worth noting that you're not testing a practical solution anyway, since in real life you'll need to do some stream setup and such to initialise your newly accepted Socket which you could do in the same thread that's accepting the connections. If you change your code accordingly there's a good change it will work right away. Also, your problem will be fixed by having your accept thread wait a number of milliseconds before accepting a new connection. Although this isnt the most clean approach imaginable it does give other threads some time to breathe if you get a large amount of simultaneous connection requests. It's a fair bet a sleep(1) will already fix your problem.
Perhaps it's a good idea to add a little more code and move closer to your goal application, and see if the problem fixes itself. You'll need a work-around anyway since it's unexpected behaviour.
Good luck.

Similar Messages

  • I have created a form which needs to be completed once a week for 6 weeks. On completing week 1, weeks 2 - 6 are completed at the same time with week 1 information. please help?

    I have created a form which needs to be completed once a week for 6 weeks. On completing week 1, weeks 2 - 6 are completed at the same time with week 1 information. please help?

    Hello, thanks for replying.
    Yes they just copy to the next page, the fields are the same. The document is an observation to school lessons so it needs to be consistent but with different data on.

  • When two Computers are online at the same time, constantly losing internet connection

    I recently added a WRT160N router to my PC for a wireless Laptop elswhere in the house as well as adding a new network adapter card to my PC. When both the Laptop and the PC are online at the same time I am constantly getting booted offline and having to reset the connection, but when just the PC is on there are no prbloems and everything seems to work fine.
    Any suggestions would be helpful, thanks in advance
    Andy

    In this case i think you need to change some settings on your Router. Follow the steps below.
    Open an Internet Explorer browser page on your wired computer(desktop).In the address bar type - 192.168.1.1 and press Enter...Leave username blank & in password use admin in lower case...
    For Wireless Settings, please do the following : -
    Click on the Wireless tab
    - Here select manual configuration...Wireless Network mode should be mixed...
    - Provide a unique name in the Wireless Network Name (SSID) box in order to differentiate your network from your neighbours network...
    - Set the Radio Band to Standard-20MHz and change the Standard channel to 11-2.462GHz...Wireless SSID broadcast should be Enabled and then click on Save Settings...
    Please make a note of Wireless Network Name (SSID) as this is the Network Identifier...
    For Wireless Security : -
    Click on the Sub tab under Wireless > Wireless Security...
    Change the Wireless security mode to WEP, Encryption should be 64 bit.Leave the passphrase blank, don't type in anything...Under WEP Key 1 type in any 10 numbers please(numbers only and no letters eg: your 10 digit phone number) and click on save settings...
    Please make a note of WEP Key 1 as this is the Security Key for the Wireless Network...
    Click on Advanced Wireless Settings
    Change the Beacon Interval to 75 >>Change the Fragmentation Threshold to 2304, Change the RTS Threshold to 2304 >>Click on "Save Settings"...
    Now see if you can locate your Wireless Network and attempt to connect...

  • Peer-to-Peer Transactional Replication (three or more participating databases): What if all the nodes are working at the same time

    In the topologies that have three or more participating databases.
    What if all nodes are working at the same time? "The topology is not partitioned by time.".
    location 1 will do insert/update/delete/read in the same time location 2 also will do insert/update/delete/read  .......
    **Data that will be added by each location is different(each location has its own primary key ranges).
    Is it recomended to use Peer-to-Peer Transactional Replication in such scinarios?

    Read these
    https://msdn.microsoft.com/en-us/library/ms151196.aspx
    http://www.brentozar.com/archive/2012/01/highly-available-local-replication/
    The only problem that you have to tackle is what happens when the same data is being updated in multiple locations at the same time. If that is not a possibility with you then p2p is a good choice. Check the above links you will have a better understanding.
    Regards, Ashwin Menon My Blog - http:\\sqllearnings.com

  • For the past month, I've had an echo of my voice while I'm talking on my phone.  It's very annoying and sounds like multiple people are speaking at the same time and it's only me.  Anyone know what's wrong?

    For the past month, I've had an echo of my voice while I'm talking on my phone.  It's very annoying and sounds like multiple people are speaking at the same time and it's only me.  Anyone know what's wrong?

    For the past month, I've had an echo of my voice while I'm talking on my phone.  It's very annoying and sounds like multiple people are speaking at the same time and it's only me.  Anyone know what's wrong?

  • New IPhone and Ipad air are ringing at the same time...

    New IPhone and Ipad air are ringing at the same time, from incoming landline/mobile phones. Help please...

    That's a new feature introduced in iOS 8 called Handoff. You can start something on your iPhone and finish it on your iPad or Mac. You can make the iPad stop ringing by going to Settings>FaceTime on the iPhone and toggling off iPhone Mobile Calls. You can do it on the iPad also.

  • Are there any apps for having seperate volume controls for each app if multiple apps are playing at the same time?

    Are there any apps for having seperate volume controls for each app if multiple apps are playing at the same time?

    I don't think you can do that the volume is universal, but maybe turn down the volumes in the app settings?

  • Illustrator CS6 crashes when 40 or more files are open at the same time

    Windows 7 SP1, Illustrator CS6
    The end users spends 7 hours of their 8 hours in Illustrator. As part of the job, they have to have over 40 different files open at the same time because they are working on several jobs at the same time as well as working forward. So the answer is not "they have to close some files". This, unfortunately, is not an option.
    We recently upgraded them to CS6. They said that version CS5 was fine and didn't crash like this. But Illustrator CS6 crashes on them, closes itself, and obviously they lose all unsaved changes (saving the changes isn't a choice either, because the files are shared and have to stay original).
    The only modification we've done to the program is to UNcheck "Append" in the preferences.
    This happens on all 3 computers for all 3 users, so I don't believe it to be end-user related.
    Does anyone out there know of a way to get Illustrator to stop crashing?
    Is there a specific limit on the number of files that can be open?
    Thanks,
    Spencer

    No, they aren't working on the same files. All 3 employees are working on different files.
    They are all on Dell Optiplex GX745 with 4 Gb of RAM.
    The crashes are at different times, not all 3 crashing at the same time. Therefore, I don't believe network is the cause of the issues. Also, it didn't crash on CS5, but now it does on CS6.
    What I'm looking for are possible settings within Illustrator CS6 that I can tweak to make it a more stable program.
    Thanks

  • Issues when Insert and Analyze at the same time

    Hi All,
    We have a weekend job that used to take 12-15 hours usually and insert around 8 millions of records to a table from external table. Last weekend the same load took 60 hours and it move to Monday and there are some business impact.
    While we investigate the same issue we identified that there is one more weekend analyze job for all the tables and indexes and took around almost same time and we noticed that the table we inserted the 8 million records alone it took around 15 hours. This table now has around 91 Core records.
    We need to identify why this jobs taken long time as almost 4 times compare to the normal scenario.
    I would like to know what exactly happen when Analyze and insert happened to the table at the same time. And What all issues can occur because this.
    Best Regards,
    Shijo

    Ok,
    It is unclear what version you are using as you forgot to post that.
    Furthermore it is unclear what 'Analyze' is, as analyze statistics was already deprecated in 9i.
    Secondly, most people is this forum speak English, and they are accustomed international units only.
    Sybrand Bakker
    Senior Oracle DBA

  • FRM: 10270 Cannot attach the library when two forms run at the same time

    I get the error message FRM: 10270 Cannot attach the library SYSLIB while opening menu BMENU but only when i try to open a second form while the first form is still running.
    Both forms are working fine as long as they ar not running at the same time.
    It seems like the second form opening does not have access to the FORMS60_PATH, because you can not open a third form because it can't find it.
    All the forms anf libraries (plx)is in the FORMS60_PATH.
    I am running developer_6i forms & reports on a HPUX 11i machine and I am trying to access them through jinitiator 1.3.1.9 on a XP machine.
    Best regards
    Macke

    Thanks a lot for the tip. I used truss and realised that it found the library but was not allowed to open it. The kernel parameter maxfiles was set to low.
    I increased it and everything works ok
    BR
    Marcus

  • Please can someone explain how to retrieve deleted text, I was clearing old text when one came through at the same time so was also deleted.

    Can someone please tell me how to retrieve deleted text. i was clearing old texts when a new one came through at the same time and was deleted also.  My last update was  iOS 8.1.2

    You restore from a backup that was created after the text was received but before it was deleted.
    But if you literally deleted it right after it came in, then it's not recoverable.  Have the other person resend the text.

  • Does MagSafe 2 T Connector get hot when charging and using at the same time (while the light still in amber) ?

    Hi,
    Just want to check out with the other Apple Users here. I am using a Late 2013 rMBP, however the T Connector do get hot while I am charging and using the mac at the same time. Is this normal ? or do I have to drop by an Apple Store to check it out ?
    Thanks in advance

    Hello there.
    It's quite normal for the magsafe 2 connector (magnetic one) to become a bit warm while it's charging your mac. It will be warmer when your battery is low and the heat will start to dissipate as the battery charges. There is absolutely nothing to worry about. Normally your magsafe can go upto 35℃ depending your surrounding temperature. Even mine does. Just remember the warmth should not be untouchable, if that is what you feel take to a apple genius bar to get it checked.
    Hope that helps.
    Thank you.

  • Streaming from ipod/ipad to ATV2 interrupted when using other apps at the same time.

    Hi.  I have an Apple TV2, ipad1 and ipod touch4.  I am having trouble with music streaming to the ATV2.  I can select a song on the ipad/itouch and stream it to the ATV2 no problem using airplay.  However, if I then try to surf the net on the ipad/itouch or use any other app at the same time as listening to the music, the music hiccups.  It seems to me like the ipad/itouch need to use the wifi network at the same time and so they take over the signal momentarily.  Any ideas what I can do about this?  My wireless router is a dual band 2.4 and 5 mhz gigabit router that is brand new and should not have any problems.
    Thanks
    Julia

    Ferrell, I have done what you suggested. I clicked onto the Spaces icon in the upper control panel and assigned spaces to six apps: Mail, Safari, iPhoto, iMovie, Pages, and iWeb.
    The problem is that if I am one app and I want to put something into that app, then the minute my mouse cursor goes to get that other thing, the original application into which I want the thing put GETS WHOOSHED OFF THE DESKTOP. What I want is for the original app to remain open whilst I go to retrieve a file or folder, and stay open while I put that thing into the original app.
    How does one turn off Spaces? I don't mean to delete all the names from the settings.I mean, just turn it off for a while so I can do something which requires for two apps to be open at the same time????
    ~ Lorna in Southern California

  • Cant get list of files from a folder (even though the folder and files are created with the same app)

    Ok so each character rolled with my app gets saved as an html file in a folder i create on the sdcard called RpgApp
    the code to do this is 
    private async Task saveToHtmlCharacter(string name)
    StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
    StorageFolder sdcard = (await externalDevices.GetFoldersAsync()).FirstOrDefault(); //Windows.Storage.ApplicationData.Current.LocalFolder;
    var dataFolder = await sdcard.CreateFolderAsync("RpgApp",
    CreationCollisionOption.OpenIfExists);
    var file = await dataFolder.CreateFileAsync(name+".html",
    CreationCollisionOption.ReplaceExisting);
    using (StreamWriter writer = new StreamWriter(await file.OpenStreamForWriteAsync()))
    writer.WriteLine("<html><head><title>Character File for " + z.charNameFirst + " " + z.charNameSecond + "</title></head><body>");
    //trimed for the post
    now this as i say works perfectly and i can confirm that the files show up in the "RpgApp"folder
    now the next step is to have the app read the names of each of those html files and create a seperate button for each one named for the filename and with the filename as content (later i will link them up to load the html file they are named for in a webbrowser
    panal)
    here is the code that *should* do that
    private async Task readFiles()
    z.test.Clear();
    StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
    StorageFolder folder = (await externalDevices.GetFolderAsync("RpgApp"));
    IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();
    //z.test.Add("dummy");
    foreach (StorageFile file in fileList)
    z.test.Add(file.Name);
    public async void buttonTest()
    await readFiles();
    CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
    await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    foreach (string name in z.test)
    Button button1 = new Button();
    button1.Height = 75;
    button1.Content = name;
    button1.Name = name;
    testStackPanal.Children.Add(button1);
    now i say should as what i get is an error of "A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll" (2 of them in fact one after another)
    more detailed error is at http://pastebin.com/3hBaZLQ9
    now i went through checking line after line to find the error and line that causes it is:
    StorageFolder folder = (await externalDevices.GetFolderAsync("RpgApp"));
    in the readFiles method
    i checked to make sure the case is right etc and its spot on, that IS the folder name, and remember my app creates that folder and creates the files that are inside that folder (and only files my app creates are in that folder) so it should have access
    im 100% stuck its taken me all day to get the files to save and now i cant get them to list correctly
    I have tested the button creation function with fake list data and that worked fine, as i say the error is when i tell it to look at the folder it created
    all help most greatfully recieved

    this was actually solved for me on another forum thread 
    async Task<bool> continueToReadAllFiles(StorageFolder folder)
    if (folder == null)
    return false;
    if (folder.Name.Equals("RpgApp", StringComparison.CurrentCultureIgnoreCase))
    var files = await folder.GetFilesAsync();
    foreach (var file in files)
    test.Add(file.Name);
    return false;
    var folders = await folder.GetFoldersAsync();
    foreach (var child in folders)
    if (!await continueToReadAllFiles(child))
    return false;
    return true;
    public async void buttonTest()
    test.Clear();
    StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
    var folders = await externalDevices.GetFoldersAsync();
    foreach (var folder in folders)
    if (!await continueToReadAllFiles(folder))
    break;
    //.... commented out
    ...now i say solved this is more a workaround...but it works.
    I would love to know why we cant just scan the RpgApp folder instead of having to scan the whole dc card and disregard all thats not in the RpgApp folder

  • My iPhone and my iPad are ringing at the same time when I receive a FaceTime call.

    I purchased anew iPhone 5s and an iPad Air last night. When setting up the iPad it asked did I want to use my number or my email. I thought I said email but every time my phone ring for FaceTime the iPad does the same. Please help!,,

    Many users use a free gmail.com email address for FaceTime and iMessage on their iPad.
    Using FaceTime http://support.apple.com/kb/ht4319
    Troubleshooting FaceTime http://support.apple.com/kb/TS3367
    The Complete Guide to FaceTime + iMessage: Setup, Use, and Troubleshooting
    http://tinyurl.com/a7odey8
    Troubleshooting FaceTime and iMessage activation
    http://support.apple.com/kb/TS4268
    iOS: FaceTime is 'Unable to verify email because it is in use'
    http://support.apple.com/kb/TS3510
    Using FaceTime and iMessage behind a firewall
    http://support.apple.com/kb/HT4245
    iOS: About Messages
    http://support.apple.com/kb/HT3529
    Set up iMessage
    http://www.apple.com/ca/ios/messages/
    iOS and OS X: Link your phone number and Apple ID for use with FaceTime and iMessage
    http://support.apple.com/kb/HT5538
    How to Set Up & Use iMessage on iPhone, iPad, & iPod touch with iOS
    http://osxdaily.com/2011/10/18/set-up-imessage-on-iphone-ipad-ipod-touch-with-io s-5/
    Set Up Alert Sounds
    http://www.quepublishing.com/articles/article.aspx?p=1873027&seqNum=3
    Extra FaceTime IDs
    http://tinyurl.com/k683gr4
    Troubleshooting Messages
    http://support.apple.com/kb/TS2755
    Troubleshooting iMessage Issues: Some Useful Tips You Should Try
    http://www.igeeksblog.com/troubleshooting-imessage-issues/
    Setting Up Multiple iOS Devices for iMessage and Facetime
    http://macmost.com/setting-up-multiple-ios-devices-for-messages-and-facetime.htm l
    FaceTime and iMessage not accepting Apple ID password
    http://www.ilounge.com/index.php/articles/comments/facetime-and-imessage-not-acc epting-apple-id-password/
    Fix Can’t Sign Into FaceTime or iMessage iOS 7
    http://ipadtutr.com/fix-login-facetime-imessage-ios-7/
    FaceTime, Game Center, Messages: Troubleshooting sign in issues
    http://support.apple.com/kb/TS3970
    Unable to use FaceTime and iMessage with my apple ID
    https://discussions.apple.com/thread/4649373?tstart=90
    iOS 7 allows you to block phone numbers or e-mail addresses from contacting you via the Phone, FaceTime, or Messages
    http://howto.cnet.com/8301-11310_39-57602643-285/you-can-block-people-from-conta cting-you-on-ios-7/
    How to Block Someone on FaceTime
    http://www.ehow.com/how_10033185_block-someone-facetime.html
    My Facetime Doesn't Ring
    https://discussions.apple.com/message/19087457#19087457
    How to watch FaceTime calls on the big screen with Apple TV
    http://www.imore.com/daily-tip-ios-5-airplay-mirroring-facetime
    Send an iMessage as a Text Message Instead with a Quick Tap & Hold
    http://osxdaily.com/2012/11/18/send-imessage-as-text-message/
    To send messages to non-Apple devices, check out the TextFree app https://itunes.apple.com/us/app/text-free-textfree-sms-real/id399355755?mt=8
    How to Send SMS from iPad
    http://www.iskysoft.com/apple-ipad/send-sms-from-ipad.html
    How to Receive SMS Messages on an iPad
    http://yourbusiness.azcentral.com/receive-sms-messages-ipad-16776.html
    Apps for Texting http://appadvice.com/appguides/show/apps-for-texting
    You can check the status of the FaceTime/iMessage servers at this link.
    http://www.apple.com/support/systemstatus/
     Cheers, Tom

Maybe you are looking for