Java socket bind exception

BindException: address already in use on a client socket?

I’ve got a client-server tiered architecture with the client making RPC-like requests to the server. I’m using Tomcat to host the servlets, and the Apache HttpClient to make requests to it. My code goes something like this:

 private static final HttpConnectionManager CONN_MGR = new MultiThreadedHttpConnectionManager(); final GetMethod get = new GetMethod(); final HttpClient httpClient = new HttpClient(CONN_MGR); get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); get.getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT); get.setQueryString(encodedParams); int responseCode; try < responseCode = httpClient.executeMethod(get); >catch (final IOException e) < . >if (responseCode != 200) throw new Exception(. ); String responseHTML; try < responseHTML = get.getResponseBodyAsString(100*1024*1024); >catch (final IOException e) < . >return responseHTML; 

It works great in a lightly-loaded environment, but when I’m making hundreds of requests per second I start to see this —

Caused by: java.net.BindException: Address already in use at java.net.PlainSocketImpl.socketBind(Native Method) at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:336) at java.net.Socket.bind(Socket.java:588) at java.net.Socket.(Socket.java:387) at java.net.Socket.(Socket.java:263) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:80) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:122) at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) 

Any thoughts on how to fix this? I’m guessing it’s something to do with the client trying to reuse the ephemeral client ports, but why is this happening / how can I fix it? Thanks!

Источник

Java Bind Exception

I have tried to bind these classes together like this: In Terrain class I have: So free up the port stop the program if running. otherwise change the port Thanks Deepak The bind() method of Java Socket class binds the socket to a local address.

Читайте также:  Constructors properties in java

Java Bind Exception

What would cause a TCP socket to throw «java.net.BindException: Address already in use» even when reuse address is set to true? This only occurs if the application is quickly restarted. Running on CentOS 5 linux OS.

Sometimes, you might notice, you try to rerun a server and bind() fails, claiming «Address already in use.» What does that mean? Well, a little bit of a socket that was connected is still hanging around in the kernel, and it’s hogging the port. You can either wait for it to clear (a minute or so), or add code to your program allowing it to reuse the port, like this

(provides C code)

Basically, in C, you call a function called setsockopt(), and one of the parameters is called SO_REUSEADDR, which lets you reuse that port.

I found some brief links on google which should get you started figuring out how to set the equivalent option in Java:

If what you say is correct you should be able to trap this exception in a loop and try again after a few seconds. (You shouldn’t have to do this, but I have heard of a few odd things about CentOS)

Java Bind Exception occurs If either of your port or inetaddress is already used and you want to use once again. So free up the port stop the program if running. otherwise change the port

Equivalent of C++’s std::bind in Java?, This is as close as I think you can get to a line by line translation, bind does not map 1:1 to any Java construct; static void PrintStringInt (String s, int n) < System.out.println (s + ", " + n); >static void PrintStringString (String s, String s2) < System.out.println (s + ", " + s2); >interface MyCall < void fn (String value); >…

Java Socket bind() method

The bind() method of Java Socket class binds the socket to a local address. If the specified address is null, then the system will automatically pick up a port number and a valid local address to bind with the socket.

Syntax

public void bind(SocketAddress bindpoint) throws IOException

Parameter

The parameter ‘bindpoint’ represents the SocketAddress to bind.

Return

Throws

IOException — if the bind operation fails, or if the socket is already bound.

IllegalArgumentException — if the bindpoint is a SocketAddress subclass not supported by this socket.

SecurityException — if the security manager exists and its checkListen method doesn’t allow the bind to the local port.

Example 1

import java.io.IOException; import java.net.*; public class JavaSocketBindExample1 < public static void main(String[] args) throws IOException < Socket socket = new Socket(); InetAddress inetAddress=InetAddress.getByName("localhost"); //the port should be greater or equal to 0, else it will throw an error int port=1085; //calling the constructor of the SocketAddress class SocketAddress socketAddress=new InetSocketAddress(inetAddress, port); //binding the socket with the inetAddress and port number socket.bind(socketAddress); System.out.println("Inet address: "+socket.getInetAddress()); System.out.println("Port number: "+socket.getLocalPort()); >>
Inet address: null Port number: 1085

Example 2

import java.io.IOException; import java.net.*; public class JavaSocketBindExample2 < public static void main(String[] args) throws IOException < Socket socket = new Socket(); InetAddress inetAddress=InetAddress.getByName("localhost"); //the port should be greater or equal to 0, else it will throw an error int port=-1085; //calling the constructor of the SocketAddress class SocketAddress socketAddress=new InetSocketAddress(inetAddress, port); //binding the socket with the inetAddress and port number socket.bind(socketAddress); System.out.println("Inet address: "+socket.getInetAddress()); System.out.println("Port number: "+socket.getLocalPort()); >>
Exception in thread "main" java.lang.IllegalArgumentException: port out of range:-1085 at java.net.InetSocketAddress.checkPort(InetSocketAddress.java:143) at java.net.InetSocketAddress.(InetSocketAddress.java:188) at com.javaTpoint.JavaSocketBindExample2.main(JavaSocketBindExample2.java:12) 

Example 3

import java.io.IOException; import java.net.*; public class JavaSocketBindExample3 < public static void main(String[] args) throws IOException < Socket socket = new Socket(); InetAddress inetAddress=InetAddress.getByName("localhost"); //the port should be greater or equal to 0, else it will throw an error int port=1085; //calling the constructor of the SocketAddress class SocketAddress socketAddress=new InetSocketAddress(inetAddress, port); //closing the socket socket.close(); //binding the socket with the inetAddress and port number //It will throw an exception, as the socket is already closed socket.bind(socketAddress); System.out.println("Inet address: "+socket.getInetAddress()); System.out.println("Port number: "+socket.getLocalPort()); >>
Exception in thread "main" java.net.SocketException: Socket is closed at java.net.Socket.bind(Socket.java:625) at com.javaTpoint.JavaSocketBindExample3.main(JavaSocketBindExample3.java:17)

Java — Conditional Binding, Then create the binding function: BooleanBinding patternTextAreaBinding(TextArea textArea, Pattern pattern) < BooleanBinding binding = Bindings.createBooleanBinding(() ->pattern.matcher(textArea.getText()).matches(), textArea.textProperty()); return …

How to bind two classes in java?

How can I bind together two Java classes?

I’m programming a 3D opengl program where I have several different classes. I know how to bind classes to the main class, but I can’t bind two separate classes together. I have a class Terrain where I have a list containing some data about the terrain. Then I need that data in another class called Figure which isn’t the main class. I have tried to bind these classes together like this:

Figure fig; public void bindClasses(Figure fg)
Terrain ter; public void bindTerrain(Terrain tr)

And then in both classes I call those functions. Shouldn’t that bind them and their variables? At least that’s how I have bound my classes with the main class.

Just to start off with terminology. A class is a blueprint that tells you how an instantiated object is — the moment you write new Figure() , you’ve created an instance, an object of the class Figure (often you have several objects of one class ). So when you are «binding» above, you are not actually binding classes, you are binding objects .

The above code is fine. By convention, you often write that sort of things with setters , it’s not necessary to call them that, but a very common pattern is:

public class Terrain < Figure fig public void setFigure(Figure fig) < this.fig = fig; >> public class Figure < Terrain ter public void setTerrain(Terrain ter) < this.ter = ter; >> 

To associate the two together you would in your main class do, which, as you see, is pretty much exactly what you would have already, just using the conventional names.

If there’s a relationship between the two objects, for instance, you can’t create a figure without having a terrain to put it in. Which would make terrain almost «own» figure. You could indicate this by using the constructor on figure.

Now your init code would instead look:

two way binding like yours is possible but is «tricky» from a design points view as well as technical.

public void addFigureToTerrain(Figure f) < //addFigureToTerrainList f.registerTerrain(this); >

now I would recommend you think carefully if you need this kind of linkage between the classes ?

usually it is simpler and more practical to have a general object (terrain) that contains a list of objects(figures). then the general object interogates/updates the list (for examples: figure.hasRecievedEventAttack(attack) or figure.whatDoYouWantToDo()) and then the general object(terrain) analyses a answer

For this situation you can use Inversion of Control (IoC) design pattern. An example is Dependency Injection which is a specific implementation of IoC

With this pattern you can avoid the coupling you have between your Terrain and Figure class. (Terrain depends on Figure and Figure depends on Terrain).

In few words you have a Container that will take care of «injecting» the attributes needed for each object so you don’t have to hardcode it.

Spring is a container that does this.

Networking — Is binding to 0.0.0.0 in Java guaranteed to, Using 0.0.0.0 will only bind to IPv4-enabled interfaces. However, if you bind to . that should cover all IPv4 and IPv6 interfaces, assuming your TCP/IP stack (and Java) have IPv4-compatible IPv6 sockets enabled.. You’ll need to look to the kernel (or socket libraries, if you’re on Windows) for an explanation of «why». On my OS …

Is binding to 0.0.0.0 in Java guaranteed to bind to all network interfaces?

I’ve found empirically that

Endpoint endpoint1 = Endpoint.create(new Ping()); endpoint1.publish("http://0.0.0.0:8080/ws/ping"); 

binds to all network interfaces on the current computer (instead of just localhost — 127.0.0.1 or the hostname), but I have not been able to locate the documentation which says that this is guaranteed.

Question: Where is it defined that binding to 0.0.0.0 in Java will always bind to all network interfaces?

Using 0.0.0.0 will only bind to IPv4-enabled interfaces. However, if you bind to :: , that should cover all IPv4 and IPv6 interfaces, assuming your TCP/IP stack (and Java) have IPv4-compatible IPv6 sockets enabled.

You’ll need to look to the kernel (or socket libraries, if you’re on Windows) for an explanation of «why». On my OS X system, the man pages explain it.

Sockets may be created with the local address INADDR_ANY to effect ‘wildcard’ matching on incoming messages. The address in a connect(2) or sendto(2) call may be given as INADDR_ANY to mean ‘this host’. The distinguished address INADDR_BROADCAST is allowed as a shorthand for the broadcast address on the primary network if the first network configured supports broadcast.

Sockets may be created with the local address :: (which is equal to IPv6 address 0:0:0:0:0:0:0:0 ) to affect ‘wildcard’ matching on incoming messages.

It has nothing to do with Java. 0.0.0.0 is INADDR_ANY, which is is a special address that is guaranteed to receive from any network interface by the C sockets API, which is called by Java.

It seems to be a special reserved IP address of sorts. This link probably has more information Is 0.0.0.0 a valid IP address?. So I suspect it is not documented in Java as it is more related to the actual network specification.

And as some others have mentioned it appears that it is the Chuck Norris IP address 😀

Address already in use: JVM_Bind java, In windows this scenario happens when Eclipse crashes without a clean shutdown it will have the local Jetty or Tomcat server keep running. When you reopen Eclipse and try to start server again this will lead to the «Address already in use: JVM_Bind». You can solve this by opening Task Manager and find the …

Источник

Getting java.net.BindException even when I close socket

I am new to socket programming and just trying my hands on a small program to get a hold of how sockets work. There’s a client and a server, and I am just trying to load some strings from server and display. But every time I make a server Socket, I get java.net.BindException , even though I manually clean up all resources in finally block. Have a look at below code and please suggest some edits on what could cause this problem. I am using Eclipse.

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class AdviceServer < String[] adviceList = < "Take smaller bites", "Go for the tight jeans. No they do NOT" + "make you look fat.", "One word: inappropriate", "Just for today, be honest. Tell your" + "boss what you *really* think", "You might want to rethink that haircut." >; public void setUpServer() < ServerSocket serverSocket = null; try < if (serverSocket == null) serverSocket = new ServerSocket(8003); int i = 2; // Keep looping till we have clients. while (true) < Socket sock = serverSocket.accept(); PrintWriter pw = new PrintWriter(sock.getOutputStream()); pw.write(getRandomAdvice()); pw.close(); System.out.println(getRandomAdvice()); >// serverSocket.close(); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >finally < if (serverSocket != null) < try < serverSocket.close(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > > public void setUpClient() < // Make a socket Socket chatSocket = null; try < chatSocket = new Socket("127.0.0.1", 8003); InputStreamReader isr = new InputStreamReader( chatSocket.getInputStream()); // Make a chain stream Buffered Reader BufferedReader br = new BufferedReader(isr); String text; while ((text = br.readLine()) != null) < System.out.println(text); >br.close(); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >finally < if (chatSocket != null) < try < chatSocket.close(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > > public String getRandomAdvice() < return adviceList[(int) (Math.random() * adviceList.length)]; >public static void main(String[] args) < AdviceServer as = new AdviceServer(); as.setUpClient(); as.setUpServer(); >> 

Yeah, I have tried different ports, other than this too, 5000, 6000, 8002, etc.. But I get the same exception every time. What are you getting when you run this on Eclipse?

Источник

Оцените статью