This question already has answers here:
Exception in thread "main" java.net.BindException: Address already in use - Error in Netbeans only
(6 answers)
Closed 7 years ago.
I am trying to run the following code by first running the chatserver file and then the chatclient file.
import java.net.*;
import java.io.*;
public class chatserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket sk=ss.accept();
BufferedReader cin=newBufferedReader(newInputStreamReader(sk.getInputStream()));
PrintStream cout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
s=cin.readLine();
if (s.equalsIgnoreCase("END"))
{
cout.println("BYE");
break;
}
System. out.print("Client : "+s+"\n");
System.out.print("Server : ");
s=stdin.readLine();
cout.println(s);
}
ss.close();
sk.close();
cin.close();
cout.close();
stdin.close();
}
}
public class chatclient
{
public static void main(String args[]) throws Exception
{
Socket sk=new Socket("192.168.0.19",2000);
BufferedReader sin=new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();
System.out.print("Server : "+s+"\n");
if ( s.equalsIgnoreCase("BYE") )
break;
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
}
But it is not working. What are the correct procedure/steps to run a this kind of application?
Running the server file gives the following error.
Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:382)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at javaapplication1.chatserver.main(chatserver.java:19)
Java Result: 1
Address already in use means some program is already listening on port 2000 (most likely the same program that you didn't shutdown properly).
Try out a different port.
You may use the netstat command on your command line to see which ports are currently in use.
Here is your working example:
// Server
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public Server() {
// TODO Auto-generated constructor stub
}
public static void main(String args[]) throws Exception
{
System.out.println("Server started");
ServerSocket ss=new ServerSocket(8888);
System.out.println("Server waiting for connection");
Socket sk=ss.accept();
System.out.println("Server Connected");
BufferedReader cin=new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintStream cout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
s=cin.readLine();
if (s.equalsIgnoreCase("END"))
{
cout.println("BYE");
break;
}
System. out.print("Client : "+s+"\n");
System.out.print("Server : ");
s=stdin.readLine();
cout.println(s);
}
ss.close();
sk.close();
cin.close();
cout.close();
stdin.close();
}
}
// Client
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public Client() {
// TODO Auto-generated constructor stub
}
public static void main(String args[]) throws Exception
{
System.out.println("Client started");
Socket sk=new Socket("localhost",8888);
System.out.println("Client Connected");
BufferedReader sin=new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();
System.out.print("Server : "+s+"\n");
if ( s.equalsIgnoreCase("BYE") )
break;
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
}
Address already in use: JVM_Bind
Java application is trying to connect on port 2000 but that port is already used by some other process and JVM Bind to that particular port 2000, is failed. Now to fix this error you need to find out which process is listening of port 2000
Windows users:
In Command Prompt, send command "netstat -ao". You can get network information for all processes.
Find out the one using port 2000, get the PID.
Find out the process with the PID you just got from windows task manager and shut it down. (By default the Task Manager doesn't show the PID. You have to add it from the menu View | Select columns)
Restart Server.
Restart the application you've just shutdown.
Unix users:
Most Unix systems have the built-in fuser command that returns the process which is engaging a port:
fuser -v -n (tcp | udp) <port#>
but if you can not kill that process than you need to change your web-server configuration or eclipse configuration to listen on different port. In case of tomcat you can change it on connector section of server.xml and in case of eclipse you can see here setting up Eclipse for Java remote debugging.
Change the port number you are using to run your application.
For more check this link- http://www.mastertheboss.com/jboss-server/jboss-configuration/solving-javanetbindexception-address-already-in-use-jvmbind
your port 2000 is already in use by another process.
try using the netstat command on your commandline to see which port are in use.
I usually use 5 digit ports like 10999 which is uncommon.
You are using the same port for both client and server: 2000, that's why starting client fails because only one process can use a socket, so if server takes it then client can't.
Related
This is the server side code
I'm pretty sure the error is that the Server Socket Isn't closing the port?
There is no problem when I run the program but, When I run it again I get this Error:
Exception in thread "main" java.net.BindException: Address already in use: bind
at java.base/sun.nio.ch.Net.bind0(Native Method)
at java.base/sun.nio.ch.Net.bind(Net.java:550)
at java.base/sun.nio.ch.Net.bind(Net.java:539)
at java.base/sun.nio.ch.NioSocketImpl.bind(NioSocketImpl.java:643)
at java.base/java.net.ServerSocket.bind(ServerSocket.java:396)
at java.base/java.net.ServerSocket.<init>(ServerSocket.java:282)
at java.base/java.net.ServerSocket.<init>(ServerSocket.java:173)
at internet.server.main(server.java:11)
But if I change the port number it fixes for that one time running. Someone please help also I haven't learned java server sockets or client sockets yet soo I need help as far as I know no one else is having this problem
package internet;
import java.io.IOException;
import java.net.*;
import java.io.*;
public class server {
public static void main(String[] args) throws IOException {
println("Compiled");
ServerSocket ss = new ServerSocket(5502);
Socket s = ss.accept();
println("Client Connected!");
InputStreamReader in = new InputStreamReader(s.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str = bf.readLine();
println("Client: " + str);
s.close();
ss.close();
}
public static void println(String args) {
System.out.println(args);
}
}
This will works fine as long as you terminate your previous execution before you re run it.
Try closing those streams, InputStreamReader and BufferedReader as well. Close them before socket and ServerSocket.
bf.close();
in.close();
This question already has answers here:
How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?
(22 answers)
Closed 5 years ago.
I've wrote these two classes, one for client and the other for server. When I run both of them I get the following error:
java.net.BindException: Address already in use: JVM_Bind...
What is the problem? Also I use TCPview software and there were just two java.exe that use the same port. These two java.exe processes belong to the apps.
Here is the code:
Server Code
/**
*
* #author casinoroyal
*/
public class server {
public static ServerSocket socket1;
public static void main(String[] args) {
try {
socket1 = new ServerSocket(1254);
String request="";
Socket mylink=socket1.accept();
System.out.println("server feels=====");
DataInputStream input= new DataInputStream(mylink.getInputStream());
DataOutputStream output=new DataOutputStream(mylink.getOutputStream());
Scanner chat=new Scanner(System.in);
while(!request.equals("QUIT")){
request=input.readUTF();
output.writeUTF(chat.next());
}
socket1.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
}
Client Code
package javaapplication9;
import java.net.*;
import java.io.*;
import java.util.*;
public class client {
//main
public static void main(String[] args) {
System.out.println("client want to be connected");
try {
Socket mysock = new Socket(InetAddress.getLocalHost(),1254);
System.out.println("client has been connected");
DataInputStream input = new DataInputStream(mysock.getInputStream());
DataOutputStream output = new DataOutputStream(mysock.getOutputStream());
String reque="";
Scanner scan1=new Scanner(System.in);
String sendmsg=scan1.next();
while(!reque.equals("QUIT")){
output.writeUTF (sendmsg);
reque=input.readUTF();
}
mysock.close();
} catch (IOException ex) {
System.out.println("client rejected"+ex);
}
}
}
What is the problem? Also I use TCPview software and there were just two java.exe that use the same port. These two java.exe processes belong to the apps.
Here is your problem.
You tried to bind 2 sockets at the same port of your computer, and you can't bind 2 sockets at the same port on the same computer.
It's probably because you had an existing process that is listening at the port 1254 ( probably an instance of your server app ), and you tried to run your server app which tried to bind also at the port 1254
I am not able to connect two different machines over the same network using the following client server programs.
the code however runs fine on the same machine.
I think in the client program it goes in an infinite loop just before socket.accept();
please suggest a possible solution.
server.java
import java.io.*;
import java.net.*;
import java.lang.*;
class server{
public static void main(String args[]){
try{
int one,zero;
one=zero=0;
ServerSocket sock=new ServerSocket(2000);
Socket soc=sock.accept();
DataInputStream dis=new DataInputStream(soc.getInputStream());
System.out.println("Connection Established");
String msg =dis.readLine();
System.out.println("MESSAGE : "+msg);
for(int i=0;i<msg.length();i++){
if(msg.charAt(i)=='0')
zero++;
else
one++;
}
System.out.println("Ones are "+one);
System.out.println("Zeros are "+zero);
soc.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
client.java
import java.io.*;
import java.net.*;
class client{
public static void main(String args[]){
try{
Socket soc=new Socket("localhost",2000);//or ipv4 address for different computers
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
PrintStream pr=new PrintStream(soc.getOutputStream());
System.out.println("Enter message..");
String msg =is.readLine();
pr.println(msg);
System.out.println("YOU ENTERED.."+msg);
soc.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
I had the same problem and here is how I figured it out : UDP Broadcast. It will allow the client to connect to server regardless of its IP, so you don't have to hardcode the IP Address, only the port used for UDP (see below).
Here is how it works :
1.Server watch port n
2.Client send message at all port n he can reach
3.When a message reach server's port, Server response with to the sender and include its IP address
4.Client create a socket and connect to the IP address he got from the server
Here is the tutorial that helped me : http://michieldemey.be/blog/network-discovery-using-udp-broadcast/
I Tried to run a Java socket in mac with eclipse but it doesn't work. I got this error:
Exception in thread "main" java.net.BindException: Permission denied
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.socketBind(PlainSocketImpl.java:521)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:414)
at java.net.ServerSocket.bind(ServerSocket.java:326)
at java.net.ServerSocket.<init>(ServerSocket.java:192)
at java.net.ServerSocket.<init>(ServerSocket.java:104)
at server.MessageServer.main(MessageServer.java:11)
How can i make it to run?
package server; //ChatServer
import java.io.*;
import java.net.*;
public class MessageServer {
public static void main (String args[]) throws IOException {
int port = 100;
ServerSocket server = new ServerSocket (port);
System.out.println("Server is started!");
while (true) {
Socket client = server.accept ();
System.out.println ("Accepted from " + client.getInetAddress ());
MessageHandler handler = new MessageHandler (client);
handler.start();
}
}
}
You can't open a port below 1024, if you don't have root privileges and from the code you posted in your comment, you seem to be trying to open port 100 which confirms my theory.
You need to use a port which is higher than 1024, if you're running the code under a non-root user.
Unix-based systems declare ports < 1024 as "privileged" and you need admin rights to start a server.
For testing, use a port number >= 1024.
When deploying the server in production, run it with admin rights.
I had the same issue and my port numbers were below 1024 changing port number to above 1024 solved my problem. Ports below 1024 are called Privileged Ports and in Linux (and most UNIX flavors and UNIX-like systems), they are not allowed to be opened by any non-root user.
Many systems declare ports that are less than 1024 as "admin rights" ports. Meaning, if you're only using this for basic testing use a higher port such as 2000. This will clear the exception that you're getting by running your current program.
int port = 100;
ServerSocket server = new ServerSocket (port);
Change that to something such as:
int port = 2000;
ServerSocket server = new ServerSocket (port);
MyServer.java
import java.io.*;
import java.net.*;
public class MyServer
{
ServerSocket ss;
Socket s;
DataOutputStream dos;
DataInputStream dis;
public MyServer()
{
try
{
System.out.println("Server Started ");
ss=new ServerSocket(4444);
s=ss.accept();
System.out.println(s);
System.out.println("Client Connected");
dis=new DataInputStream(s.getInputStream());
dos=new DataOutputStream(s.getOutputStream());
ServerChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String arg[])
{
new MyServer();
}
public void ServerChat()throws IOException
{
String str;
do
{
str=dis.readUTF();
System.out.println("Client msg : "+str);
dos.writeUTF("Hello "+str);
dos.flush();
}while(!str.equals("stop"));
}
}
MyClient.java
import java.io.*;
import java.net.*;
public class MyClient
{
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyClient()
{
try
{
s=new Socket("localhost",4444);
System.out.println(s);
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
ClientChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public void ClientChat() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s1;
do
{
s1=br.readLine();
dout.writeUTF(s1);
dout.flush();
System.out.println("Server Msg : "+din.readUTF());
}while(!s1.equals("stop"));
}
public static void main(String arg[])
{
new MyClient();
}
}
Run Server program with root (Administrator).
Windows: Run as Administrator the IDE/Editor.
Ubuntu/macOS: sudo java...
This is an old question, and I might be replying too late, but I would like to anyways share my experience in case anyone hits the issue.
I was using port# 8000, but still unable to bind to the port from a java program. It was network filter running as part of eset endpoint security that was blocking the connection.
I added a rule in eset firewall to allow port 8000, and it started working.
I am trying to implement this example here: Reading from and Writing to a Socket
I copied and pasted the code into NetBeans. I changed the port name "taranis" to "localhost" and tried to run the example, but I got the error:
run: Couldn't get I/O for the connection to: localhost. Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
I also tried to substitute localhost for my actual hostname of my laptop, but it gives the similar error. Can you help pinpoint what I am doing wrong?
Edit: In regards to Mark's recommendation, when I substitute
System.err.println("Couldn't get I/O for " + "the connection to: localhost.");
with
e.printStackTrace();
I get:
run:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at EchoClient.main(EchoClient.java:12)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
The echo service is not listening. Why not write your own? Run the application below and change your client to connect to the same port (8000).
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 EchoServer {
private static final int PORT = 8000;
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
}
catch (IOException e) {
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Echo server started");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("echoing: " + inputLine);
out.println(inputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
Btw, the next example (knock-knock server) does work and gives a nice example of using a 'protocol' class.
I don't think the echo service is running by default, when I tried a quick test it on my Win XP client, it did not work:
H:\>telnet localhost 7
Connecting To localhost...Could not open connection to the host, on port 7:
Connect failed
H:\>
So to make your code work, you could try pointing it to a server that has the echo service running.
For future reference, the echo service is commonly disabled by default. I'm using windows 7, to enable it I followed the instructions found here:
http://www.windowsnetworking.com/articles_tutorials/windows-7-simple-tcpip-services-what-how.html
Example worked fine for me afterwards.
For XP:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/sag_tcpip_pro_simptcpinstall.mspx?mfr=true