Question

2 socket connections to the same host...

Asked by: InteractiveMind

Hey guys.

I am trying to establish two Socket connections between to applications, over a network (well, I'm currently testing just on my local machine).

On the Server-application, I'm doing this:

Socket sock1;                 // Class instance
Socket sock2;                 //
...
ServerSocket srv = new ServerSocket( port );
sock1 = srv.accept();

try
{
    ServerSocket srv2 = new ServerSocket( port );
    srv2.setSoTimeout( 10 *1000 );
    sock2 = srv2.accept();
} catch ( InterruptedIOException ioe2 )
{
    error( "Timeout exception occured." );
} catch ( Exception e2 )
{
    e2.printStackTrace();
}


Then on the client-application:

Socket sock1;                // Class Instance
Socket sock2;                //
...
sock1 = new Socket( InetAddress.getByName( server ), port );
sock2 = new Socket( InetAddress.getByName( server ), port );


Obviously, it's all in try{}catch statements appropriately.. Now, when I run it, what appear to be happening, is that the first connection is made without problem, but then a problem occurs on the second connection attempt.. The server is throwing the following exception:

java.net.BindException: Address already in use: JVM_Bind
      at java.net.PlainSocketImpl.socketBind(Native Method)
      at java.net.PlainSocketImpl.bind(Unknown Source)
      at java.net.ServerSocket.bind(Unknown Source)
      at java.net.ServerSocket.<init>(Unknown Source)
      at java.net.ServerSocket.<init>(Unknown Source)
      at ConnHandler.run(ConnHandler.java:48)

Where ConnHandler.java is the Server class, and line 48 is this line:

    ServerSocket srv2 = new ServerSocket( port );

Why is it not making a second connection? What would you say is the best way to achieve this?

Regards;

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-04-08 at 04:14:45ID21381392
Tags

jvm_bind

,

address

,

already

,

socket

Topic

Java Programming Language

Participating Experts
2
Points
500
Comments
12

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. ServerSocket and UDP
    Hi, Can someone help me with the following problems: When I set up a ServerSocket and use a Socket with its stream flag set to true, everything is working fine but once I set the flag to false(ie UDP) there doesn't seem to be a connection... UDP can't be that unrealiabe...
  2. "Determining unique id of a JVM..."
    Hello experts, Imagine the following situation: Several machines are running several system processes each, that happen to be JVMs. Each JVM runs the same software, that writes a file in a network directory somewhere. This file have to be assigned unique name, so that only ...
  3. Help with ServerSocket port
    hi, i create a serversocket like such. with a port 3666 or any number for that matter. listen = new ServerSocket(port); however, everytime i call getLocalPort it is a different number. what i am trying to is set a well known port accept a connecion then send a new port to ...
  4. ServerSocket
    Hiya, I created the 'standard' echo-server using the ServerSocket. Each new connection is handled in its own thread. it all works fine with a few clients. I then wrote a small client that creates heaps of threads each trying to connect to the echo-server.. this gives me unp...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: InteractiveMindPosted on 2005-04-08 at 04:16:12ID: 13734916

do I need to do:

srv.close();

before creating the second ServerSocket? I haven't bothered trying it; because I'm guessing that it would close sock1, right?

 

by: CodingExpertsPosted on 2005-04-08 at 04:24:22ID: 13734956

sock1 = new Socket( InetAddress.getByName( server ), port );
sock2 = new Socket( InetAddress.getByName( server ), port );

would mean you are connecting to the same port twice.

Are you changing the port while connecting

CE

 

by: InteractiveMindPosted on 2005-04-08 at 04:51:40ID: 13735125

> would mean you are connecting to the same port twice
Yeah; I need two connections between the two applications, both on the same port.

> Are you changing the port while connecting
Nope.

 

by: InteractiveMindPosted on 2005-04-08 at 04:52:34ID: 13735135

By the way: I need to create both ServerSockets on the Server Application; so I can't just create a server sock on the Server app, and another Server sock on the client app...

 

by: CodingExpertsPosted on 2005-04-08 at 05:02:28ID: 13735196

This is what you should do ...


ServerSocket srv = new ServerSocket( port1 );
ServerSocket srv = new ServerSocket( port 2);

sock1 = new Socket( InetAddress.getByName( server ), port1 );
sock2 = new Socket( InetAddress.getByName( server ), port 2);

-CE

 

by: CodingExpertsPosted on 2005-04-08 at 05:03:07ID: 13735201

Typo error ... it should be ..

ServerSocket srv1 = new ServerSocket( port1 );
ServerSocket srv2 = new ServerSocket( port 2);

-CE

 

by: InteractiveMindPosted on 2005-04-08 at 05:09:53ID: 13735257

But, I need both ports to be the same...

 

by: CodingExpertsPosted on 2005-04-08 at 05:16:08ID: 13735312

When a ServerSocket object is created, it attempts to bind to the port on the local host given by the port argument.

If another server socket is already listening to the port, then a java.net.BindException, a subclass of IOException, is thrown.

No more than one process or thread can listen to a particular port at a time. This includes non-Java processes or threads.

For example, if there's already an HTTP server running on port 80, you won't be able to bind to port 80.

-CE

 

by: InteractiveMindPosted on 2005-04-08 at 05:22:29ID: 13735359

But, from my first attempt, what it *should* do (at least, what I would expect it to do), is listen on the 'port', then block until it accepts a connection, with this command:

sock1 = srv.accept();

Then, that should stop it from listenning on that port... right? And then, I can create a new ServerSocket on that same port..?

Or, do I need to do something like this:

ServerSocket srv1 = new ServerSocket( port );
sock1 = srv1.accept();
srv1.close();

ServerSocket srv2 = new ServerSocket( port );
sock2 = srv2.accept();
srv2.close();

??

 

by: guitaristxPosted on 2005-04-08 at 08:55:37ID: 13737596

If you're only wanting the server to accept connections through one port, you only need one ServerSocket object.  However, you need to spawn a new thread each time the ServerSocket's accept() method returns.

<pseudocode alert!>

ServerSocket svr = new ServerSocket( port );
Socket s = srv1.accept();
while( some_condition )
{
     MySocketThread t = new MySocketThread(s);
     t.start();
     s = srv1.accept();
}

<and elsewhere in the server>
public class MySocketThread extends Thread
{
     private Socket s;

     public MySocketThread(Socket sock)
     {
          s = sock;
     }

     public void run()
     {
          //do your server-side stuff here
     }
}

 

by: guitaristxPosted on 2005-04-08 at 08:57:18ID: 13737623

The above code makes certain that there is a minimum amount of time taken when the ServerSocket is not accepting connections.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...