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.
Related
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.
Note: I found a similar question here:
How to close port after using server sockets
But did not find any satisfactory answer there.
Here is my code for the client program:
package hf;
import java.io.*;
import java.net.*;
public class DailyAdviceClient
{
private static final int chatPort = 4242;
public static void main(String[] args)
{
DailyAdviceClient client = new DailyAdviceClient();
client.go();
}
private void go()
{
try
{
Socket socket = new Socket("127.0.0.1",chatPort);
InputStreamReader inputStream = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStream);
String advice = bufferedReader.readLine();
System.out.println("Advice received by the client for today is "+advice);
bufferedReader.close();
}
catch(Exception e)
{
System.out.println("Failed to connect to the server");
}
}
}
And here is the code for the server program:
package hf;
import java.io.*;
import java.net.*;
public class DailyAdviceServer
{
private 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."};
private static final int chatPort = 4242;
public static void main(String[] args)
{
DailyAdviceServer server = new DailyAdviceServer();
server.go();
}
private void go()
{
try
{
ServerSocket serverSocket = new ServerSocket(chatPort);
while(true)
{
Socket socket = serverSocket.accept();
PrintWriter writer = new PrintWriter(socket.getOutputStream());
String advice = getTodaysAdvice();
writer.println(advice);
writer.close();
}
}
catch(Exception e)
{
System.out.println("Error in establishing connection with the client");
}
}
private String getTodaysAdvice()
{
String advice = null;
int randomIndex = (int) (Math.random()*adviceList.length);
advice = adviceList[randomIndex];
return advice;
}
}
In the application, whenever a client program connects to the server program, it receives a String that contains advice for the day.
When I run
netstat -an
In the command prompt of my Windows computer as suggested in one of the answers in the aforementioned link, I get a message that the port 4242 is
LISTENING
How do I close the port and make it available for future re-use?
To get rid of the LISTENING port you have to call serverSocket.close().
You have to use socket.close() after closing the writer and bufferedReader. So the Port will be free for another communication.
I have a simple pair of client and server programs. Client connects to server and when it does connect, the server replies with a "Hello there" message. How should I modify the program if I want the client and server programs to run on different systems?
Here is the code for the client side..
package practice;
import java.io.*;
import java.net.*;
public class DailyAdviceClient
{
public static void main(String args[])
{
DailyAdviceClient dac = new DailyAdviceClient();
dac.go();
}
public void go()
{
try
{
Socket incoming = new Socket("127.0.0.1",4242);
InputStreamReader stream = new InputStreamReader(incoming.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String advice = reader.readLine();
reader.close();
System.out.println("Today's advice is "+advice);
}
catch(Exception e)
{
System.out.println("Client Side Error");
}
}
}
and here is the code for the server
package practice;
import java.io.*;
import java.net.*;
public class DailyAdviceServer
{
public static void main(String args[])
{
DailyAdviceServer das = new DailyAdviceServer();
das.go();
}
public void go()
{
try
{
ServerSocket serversock = new ServerSocket(4242);
while(true)
{
Socket outgoing = serversock.accept();
PrintWriter writer = new PrintWriter(outgoing.getOutputStream());
writer.println("Hello there");
writer.close();
}
}
catch(Exception e)
{
System.out.println("Server Side Problem");
}
}
}
just change "127.0.0.1" on the client with the server's IP and make sure the port 4242 is open.
Socket incoming = new Socket("127.0.0.1",4242);
This is creating a socket listening to the server at the address 127.0.0.1 on port 4242. If you change the server to another address, for example of a different pc, then change the ip address that your socket is listening to.
It is also worth noting that you will probably have to open up or allow access to the ports you are using.
Client requires ip address and port of server, means ip of that system which you making server and port (4242).so in client you need to change
Socket incoming = new Socket("127.0.0.1",4242); BY
Socket incoming = new Socket("IP address of server",4242);
And make sure both system is connected via wired or wireless network.
I have written a program on Socket Programming, and I created a client and a server. Codes for both are as follows:
CLIENT:
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
SERVER:
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Now, I am unable to run the program in Eclipse, can anyone help me, how to do this ?
Go to RunConfigurations.. and click on the Class Name(as here 'GreetingClient') under the java application in the left pane of RunConfiguration window
on the right side you will get many tab like Main,Arguments,jre,ClassPath etc so now click on the 'Arguments'
below this tag you will get textbox with label Program arguments:
here in this textbox you need to pass your command line argument
for multiple values give single space between the argument values then click on the Apply button
like in above case you need to pass commandline argument twice.
so first you configure for the GreetingServer and then for the GreetingClient and then apply and run one by one
click on the GreetingServer.java and then right click on mouse and select Run As-->Run Configuration.. then go to Java Application and click
GreetingServer -->Argument--> 6000 -->apply and -->run
output like this
Waiting for client on port 6000...
now click on the GreetingClient.java and then right click on mouse and select Run As-->Run Configuration.. then go to Java Application and click
GreetingClient -->Argument--> 127.0.0.1 6000 -->apply and -->run
then you will get your application running and
output like this
Connecting to 127.0.0.1 on port 6000
Just connected to /127.0.0.1:6000
Server says Thank you for connecting to /127.0.0.1:6000
Goodbye!
Any port you can send it your wise just keep in mind port no. should be free
for the eclipse argument passing you can go through this link
Actually, you need to run the programs individually in the
Eclipse-IDE. The output will be indented one on another in next tab on
the output area.
I don't have info about Eclipse.
In Netbeans,you need to run the Client.java file separately. Then,move
to Server.java file and run it separately. You'll see at the bottom
that two windows---one running Client.java and the other running
Server.java will be running independently. Now,send message from
client to server and vice-versa.
EDIT FOR YOUR COMMAND LINE PARAMETER SETTING IN ECLIPSE IDE :-
Go to Project--> Run --> Run Configurations --> Arguments.!
Pass the arguments as
args[0]=127.0.0.1 //local-host
args1=3000 //say 3000,you can give any port no. but take care that it should exist!
Try running the Client program first and then run the server program in Netbeans, the program will run with no problem...
/*Server*/
import java.net.*;
import java.io.*;
public class MyServer
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(8100);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
str=din.readUTF();
System.out.println("clint Says"+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
Do I have to close all the sockets after using it? Where should I put them in this code? My program just works normally when I run it. However, when I re-run it, it said "Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind". Therefore, I think I did not close all the socket after using it.
import java.io.*;
import java.net.*;
import java.util.*;
public class Server2 {
public static void main(String args[]) throws Exception {
int PORT = 5555; // Open port 5555
//open socket to listen
ServerSocket server = new ServerSocket(PORT);
Socket client = null;
while (true) {
System.out.println("Waiting for client...");
// open client socket to accept connection
client = server.accept();
System.out.println(client.getInetAddress()+" contacted ");
System.out.println("Creating thread to serve request");
ServerStudentThread student = new ServerStudentThread(client);
student.start();
}
}
}
Call server.close() in a finally block.
ServerSocket server = new ServerSocket(PORT);
try {
while (true) {
System.out.println("Waiting for client...");
// open client socket to accept connection
Socket client = server.accept();
System.out.println(client.getInetAddress()+" contacted ");
System.out.println("Creating thread to serve request");
ServerStudentThread student = new ServerStudentThread(client);
student.start();
}
} finally {
server.close();
}
Address already in use: JVM_Bind - means, that you operation system is not closed socket after previous use. It closes on timeout about 30-180 seconds.
I don't realy know how to do this in java, but in C code it may be done like this, before bind system function call:
int yes = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
That mean: set the flag (option) SO_REUSEADDR to sockfd socket.
In java must exists appropriate mechanism for do the same.
You are running an infinite while loop , have a boolean variable to say when to stop , i think you are not exiting gracefully, that is why port is not closed.
May be you can try like this
import java.io.*;
import java.net.*;
import java.util.*;
public class Server2 {
static int NUM_CONN_TO_WAIT_FOR=15;
boolean exitServer =false;
public static void main(String args[]) throws Exception {
int PORT = 5555; // Open port 5555
//open socket to listen
ServerSocket server = new ServerSocket(PORT);
Socket client = null;
static int connections =0;
try
{
while (!exitServer ) {
System.out.println("Waiting for client...");
// open client socket to accept connection
if ( connections < NUM_CONN_TO_WAIT_FOR )
{
client = server.accept();
System.out.println(client.getInetAddress()+" contacted ");
System.out.println("Creating thread to serve request");
ServerStudentThread student = new ServerStudentThread(client);
student.start();
} else
{
exitServer =true;
}
connections++;
}
} catch (Exception e)
{
System.out.println(e.printStackTrace());
}
finally
{
if ( client != null)
client.close();
if ( server!= null)
server.close();
}
}
}