简体   繁体   中英

“BindException: Address already in use” exception when transferring file using java socket in a same pc

I am very new to java network programming. I am trying to write a program that can transfer file over the network. I have write two separate program for sender and receiver. And run that two programs in two separate Intellij window in my pc. I have put the same port number in server socket as well as receiver socket. And the IP Address is the localhost. When I run that two program either of that two throws exception.

After some googling I found Java sockets: multiple client threads on same port on same machine? question where people said that it is legitimate to run two program in same port. I haven't to test this code from two different from two PC.

So my question what am I missing ? Can I run this two program in my PC simultaneously?

here is my written code -

for Sender--

public class Sender {
public static void main(String[] args) throws IOException
{
    String fileLocation;
    int portNo;
    portNo = 6000;
    fileLocation = "/files/A.cpp";
    Sender.send(portNo,fileLocation);
}
public static  void send(int portNo,String fileLocation) throws IOException
{

    FileInputStream fileInputStream = null;
    BufferedInputStream bufferedInputStream = null;

    OutputStream outputStream = null;
    ServerSocket serverSocket = null;
    Socket socket = null;
    try {
        serverSocket = new ServerSocket(portNo);
        System.out.println("Waiting for receiver...");
        try {
            socket = serverSocket.accept();
            System.out.println("Accepted connection : " + socket);

            File file = new File (fileLocation);
            byte [] byteArray  = new byte [(int)file.length()];
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            bufferedInputStream.read(byteArray,0,byteArray.length); // copied file into byteArray

            //sending file through socket
            outputStream = socket.getOutputStream();
            System.out.println("Sending " + fileLocation + "( size: " + byteArray.length + " bytes)");
            outputStream.write(byteArray,0,byteArray.length);
            outputStream.flush();
            System.out.println("Done.");
        }
        finally {
            if (bufferedInputStream != null) bufferedInputStream.close();
            if (outputStream != null) bufferedInputStream.close();
            if (socket!=null) socket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (serverSocket != null) serverSocket.close();
    }
}
}

for Receiver --

public class Receiver {

public static void main (String [] args ) throws IOException {


    String fileLocation,ipAddress;
    int portNo;
    ipAddress = "localhost";
    portNo = 6000;
    fileLocation = "/files/A.cpp";
    Receiver.receiveFile(ipAddress, portNo, fileLocation);


}
public static void receiveFile(String ipAddress,int portNo,String fileLocation) throws IOException
{
    int bytesRead=0;
    int current = 0;
    FileOutputStream fileOutputStream = null;
    BufferedOutputStream bufferedOutputStream = null;
    Socket socket = null;
    try {
        socket = new Socket(ipAddress,portNo);
        System.out.println("connected.");

        byte [] byteArray  = new byte [6022386];                    
        System.out.println("Please wait downloading file");

        InputStream inputStream = socket.getInputStream();
        fileOutputStream = new FileOutputStream(fileLocation);
        bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        bytesRead = inputStream.read(byteArray,0,byteArray.length);         

        current = bytesRead;
        do {
            bytesRead =inputStream.read(byteArray, current, (byteArray.length-current));
            if(bytesRead >= 0) current += bytesRead;
        } while(bytesRead > -1);
        bufferedOutputStream.write(byteArray, 0 , current);             

        System.out.println("File " + fileLocation  + " downloaded ( size: " + current + " bytes read)");
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (fileOutputStream != null) fileOutputStream.close();
        if (bufferedOutputStream != null) bufferedOutputStream.close();
        if (socket != null) socket.close();
    }
}
}

Thank you.

Your receiver does not need to specify a port to use, leave that to the OS (it will automatically assign a free ephemeral port number; the port number is not important).

Instead, use the Socket.connect(SocketAddress) method to connect the client socket to the server. Specifiy the socket address using the IP/Name of the server plus the port number used, eg:

InetAddress iadr = InetAddress.getByName("localhost");
SocketAddress sadr = new InetSocketAddress(iadr, portNo);
Socket socket = new Socket();
socket.connect(sadr);

This is how you normally connect to a server at a specfied port. The local (client) endpoint is not explicitly specified.

Of course, the server must already be running for this to succeed.

Edit: Since the client endpoint is automatically assigned, the OS will assign a free endpoint for every client, thus you can run multiple clients (receivers) on the same machine without any conflicts.

First it's impossible to use the same port for two serverSockets so your code should work if you don't run the Sender Class twice , you need to correct the name of your class Receiver_ to be Receiver then the steps for your code to be working are :

  • First you run Receiver Class (always start by the server)
  • Then you run Sender Class (which is the Client here)
  • if it doesn't work it might be because another program is using the port 6000, try to change it to another one like 9010 in both of your classses

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM