• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Can I use the same socket to to reconnect after the first connection failed.  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I use socket to connect first to one service, but if the connection fails (is refused)
then I want to reuse this socket to connect to different service. But when I try to
connect to second service (which I'm sure works) I get:
java.net.SocketException: Socket operation on nonsocket: connect

when I call connect() method. Does anybody know why?

The code below reproduces this problem (I use Windows XP and Java 1.5)


public class Runner {

public static void main(String[] args) throws Exception {
new Thread(new Runnable() {
public void run() {
try {
ServerSocket ss = new ServerSocket(50007);
Socket s = ss.accept();
} catch (Exception e) {
System.out.println(e);
}

}
}).start();

Thread.sleep(5000);

Socket socket = new Socket();
InetSocketAddress localAddress = new InetSocketAddress(50000);
socket.bind(localAddress);

try {
socket.connect(new InetSocketAddress("localhost", 50006));
} catch (Exception e) {
System.out.println(e);
}
try {
socket.connect(new InetSocketAddress("localhost", 50007));
} catch (Exception e) {
System.out.println(e);
}
}
}
 
Bartender
Posts: 9521
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.


java.net.Socket documentation

 
Johaness Springel
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it's true, but I don't close it explicitly. And I don't see that connect method does it. Moreover if socket was closed, then during second connection try there would be message:
java.net.SocketException: Socket is closed

(according to source code of class Socket) which is different from the one I get.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!