I am Running into a java.net.BindException: Address already in use (Bind failed) on a server-client socket app
I am trying to learn about Java sockets using a Youtube tutorial as a reference. My code seems to match everything in the video (except variables names) but, when trying to run the server and then the client sockets, I get:
Exception in thread "main" java.net.BindException: Address already in use (Bind failed)
I have tried even printing out the local port just to make sure I connect to the right available port but, nothing works. Is there any documentation I can look into to solve this problem? or any guidance?
Server.java
public class serverSocket {
public static void main(String args[]) throws IOException{
String message, serverResponse;
ServerSocket serverSocket = new ServerSocket(56789);
System.out.print(serverSocket.getLocalPort());
Socket acceptClientRequestSocket = serverSocket.accept();
Scanner serverScanner = new Scanner(acceptClientRequestSocket.getInputStream());
message = serverScanner.next();
System.out.println(message);
serverResponse = message.toUpperCase();
PrintStream newMessage = new PrintStream(acceptClientRequestSocket.getOutputStream());
newMessage.println(serverResponse);
}
}
Client.java
public class clientSocket {
public static void main(String args[]) throws UnknownHostException, IOException {
String message,outputMessage;
Scanner clientInput = new Scanner(System.in);
Socket clientSocket = new Socket("localhost",56789);
Scanner incomingStream = new Scanner(clientSocket.getInputStream());
System.out.println("Enter a message");
message = clientInput.next();
PrintStream printClientStream= new PrintStream(clientSocket.getOutputStream());
printClientStream.println(message);
outputMessage = incomingStream.next();
System.out.println(outputMessage);
}
}
Is there any documentation I can look into to solve this problem? or any guidance?
You have probably your previously exectued program still running. Check the running java processes. Kill the the previous one and try again.
If this wouldn't help try restarting your machine. If the problem persists after that then some service is already running on this port and is starting with the OS. In that case you can either change the port number in your app or disable that service.
I creating a gRPC server but everything seems to run okay but the server never starts up on the specifies port and application is throwing no errors. But when I test with telnet on that specific port, I get this from terminal
isaack$ telnet localhost 9000
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
telnet: Unable to connect to remote host
Below is my code to create the server (NB: All the services are generated okay with proto and the generated code has no errors)
import java.io.File;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerInterceptors;
import io.grpc.ServerServiceDefinition;
public class EmployeeServiceServer {
private Server server;
public static void main(String[] args) {
try {
EmployeeServiceServer service = new EmployeeServiceServer();
service.start();
} catch (Exception e) {
System.err.println(e);
}
}
private void start() throws InterruptedException {
File certificate = new File("/Users/i/certificates/cert.pem");
File key = new File("/Users/i/certificates/key.pem");
final int port = 9000;
EmployeeService employeeService = new EmployeeService();
ServerServiceDefinition serverServiceDefinition = ServerInterceptors.interceptForward(employeeService,
new HeaderServerInterceptor());
server = ServerBuilder.forPort(port).useTransportSecurity(certificate, key).addService(serverServiceDefinition)
.build();
System.out.println("Listening on Port " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("Shuttin Down Server");
EmployeeServiceServer.this.stop();
}
});
server.awaitTermination();
}
private void stop() {
if (server != null) {
server.isShutdown();
}
}
}
Below is the log from but when I ping it, I get nothing.
Listening on Port 9000
My client is throwing this error as well:
Exception in thread "main" io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:233)
at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:214)
at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:139)
at com.base.services.EmployeeServiceGrpc$EmployeeServiceBlockingStub.getBadgebyNumber(EmployeeServiceGrpc.java:373)
at com.base.client.Client.sendMetaData(Client.java:66)
at com.base.client.Client.main(Client.java:37)
Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: localhost/0:0:0:0:0:0:0:1:9000
You may want to start() your server, as build suggests:
Builds a server using the given parameters.
The returned service will not been started or be bound a port. You will need to start it with Server.start().
Perhaps that server.awaitTermination(); line could become
server.start().awaitTermination();
though I am not entirely sure.
I have faced the same error. The reason being grpc server didn't start.
Server server = ServerBuilder.forPort(port).useTransportSecurity(certificate, key).addService(serverServiceDefinition)
.build().start();
I had written start method as chain to build.
To make it work i had to call start() method separately.
server.start();
This solved the error for me.
PS: I'm writing this answer as the above solution didn't clarify much and had to research alot before finding the solution. Hope this will be helpful for other developers.
I am developing an android app, that will be communicating with an wifi controler (fixed IP and PORT) using TCP , but since i don't have the controller yet. So i created a simple C# server programm that would recieve some test messages.
But when i try to open the connection in android, it gives me the Exception:
java.net.ConnectException: failed to connect to /10.0.2.2 (port 1234): connect failed: ETIMEDOUT (Connection timed out)
C# Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Server
{
class Program
{
static byte[] Buffer { get; set; }
static Socket sck;
static void Main(string[] args)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(0, 1234));
sck.Listen(100);
Socket accepted = sck.Accept();
Buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
}
string strData = Encoding.ASCII.GetString(formatted);
Console.Write(strData + "\r\n");
Console.Read();
sck.Close();
accepted.Close();
}
}
}
Android code:
try
{
if (socket == null) {
int SERVERPORT = 1234;
InetAddress serverAddr = InetAddress.getByName("10.0.2.2");
socket = new Socket(serverAddr, SERVERPORT); // FAILS
}
}
} catch (IOException e) {
e.printStackTrace();
}
Its the first time i had to work with sockets. And i am DUMB when it comes to networking things. So it probably is a simple error.
Of course i checked all the related questions with this error, but still couldnt figure this out.
I am using GenyMotion Emulator.
Using Windows 8.1 64x.
I set the firewall settings to allow the C# app to communicate throgh windows firewall (public and private).
Does anyone know the solution? Thanks
I wrote a simple client-server application. It works very well on my computer. but when my friend tries to connect my server he can't. I create the server on my computer with port 23. Here is the part of creating the server:
public Server(int port_number) throws IOException{
create_Server(port_number);
}
public static void main(String[] args) throws IOException {
int port_number=23;
new Server(port_number);
}
private void create_Server(int port_number) throws IOException{
ss = new ServerSocket(port_number);
System.out.println("Server is ready!");
while(true){
s=ss.accept();
System.out.println(s.getLocalAddress().getHostName() + " was connected!");
send_con_mes();
list.put(s,new DataOutputStream(s.getOutputStream()) );
new ServerThread(s,this).start();
}
}
and here is the client part ;
public void start_Chat() {
try {
Ip_addr = JOptionPane.showInputDialog("Enter the IP number of the server to connect : ");
s = new Socket(Ip_addr, 23);
Client_name = JOptionPane.showInputDialog("Enter your Nickname : ");
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
new Thread(Client.this).start();
well I can talk, send private messages etc. When I connect to server on my computer as clients, but the final problem is a client from another IP cannot get connected.
You have to configure your network to allow this port to be accessed. This means enabling firewall on you PC, and your routers etc. There is nothing you can do in Java to avoid having to get this right first.
EDIT: If the other machine is trying to connect to you via an Internet router they will have to use your public IP address rather than your internal PC address. If you don't know your public address you can use a site like http://whatismyipaddress.com/. Unless you have a static IP address it can change when you reconnect. (One reason to stay connected all the time)
I have been trying to get a simple networking test program to run with no results.
Server:
import java.io.*;
import java.net.*;
public class ServerTest {
public static void main(String[] args) {
final int PORT_NUMBER = 44827;
while(true) {
try {
//Listen on port
ServerSocket serverSock = new ServerSocket(PORT_NUMBER);
System.out.println("Listening...");
//Get connection
Socket clientSock = serverSock.accept();
System.out.println("Connected client");
//Get input
BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
System.out.println(br.readLine());
br.close();
serverSock.close();
clientSock.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Client:
import java.io.*;
import java.net.*;
public class ClientTest {
public static void main(String[] args) throws IOException {
final int PORT_NUMBER = 44827;
final String HOSTNAME = "xx.xx.xx.xx";
//Attempt to connect
try {
Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
//Output
out.println("Test");
out.flush();
out.close();
sock.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
The program works just fine when I use 127.0.0.1 or my internal IP for the hostname. But whenever I switch to my external IP address, it throws a java.net.ConnectException: Connection refused: connect error.
I purposely picked such an uncommon port to see if that was the problem, with no luck.
I can connect with no problems using telnet, but when I try to access the port with canyouseeme.org, it tells me the connection timed out.
I even tried to disable all firewalls and antivirus including the Windows default ones and the router firewall, with all ports forwarded and DMZ enabled, and it still says that the connection timed out. I use Comcast as my ISP, and I doubt that they block such a random port.
When I use a packet tracer, it shows TCP traffic with my computer sending SYN and receiving RST/ACK, so it looks like a standard blocked port, and no other suspicious packet traffic was going on.
I have no idea what is going on at this point; I have pretty much tried every trick I know. If anyone know why the port might be blocked, or at least some way to make the program work, it would be very helpful.
These problem comes under the following situations:
Client and Server, either or both of them are not in network.
Server is not running.
Server is running but not listening on port, client is trying to connect.
Firewall is not permitted for host-port combination.
Host Port combination is incorrect.
Incorrect protocol in Connecting String.
How to solve the problem:
First you ping destination server. If that is pinging properly,
then the client and server are both in network.
Try connected to server host and port using telnet. If you are
able to connect with it, then you're making some mistakes in the client code.
For what it's worth, your code works fine on my system.
I hate to say it, but it sounds like a firewall issue (which I know you've already triple-checked) or a Comcast issue, which is more possible than you might think. I'd test your ISP.
Likely the server socket is only being bound to the localhost address. You can bind it to a specific IP address using the 3-argument form of the constructor.
I assume you are using a Router to connect to Internet. You should do Port Forwarding to let public access your internal network. Have a look at How do you get Java sockets working with public IPs?
I have also written a blog post about Port forwarding, you might wanna have a look :) http://happycoders.wordpress.com/2010/10/03/how-to-setup-a-web-server-by-yourself/
But I still couldn't get this accessed over public IP, working on it now...
I had the same problem because sometimes the client started before server and, when he tried to set up the connection, it couldn't find a running server.
My first (not so elegant) solution was to stop the client for a while using the sleep method:
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
I use this code just before the client connection, in your example, just before Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
My second solution was based on this answer. Basically I created a method in the client class, this method tries to connect to the server and, if the connection fails, it waits two seconds before retry.
This is my method:
private Socket createClientSocket(String clientName, int port){
boolean scanning = true;
Socket socket = null;
int numberOfTry = 0;
while (scanning && numberOfTry < 10){
numberOfTry++;
try {
socket = new Socket(clientName, port);
scanning = false;
} catch (IOException e) {
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
return socket;
}
As you can see this method tries to create a socket for ten times, then returns a null value for socket, so be carefull and check the result.
Your code should become:
Socket sock = createClientSocket(HOSTNAME, PORT_NUMBER);
if(null == sock){ //log error... }
This solution helped me, I hope it helps you as well. ;-)