使用不同端口号创建套接字时已使用的地址

时间:2014-06-20 22:58:47

标签: java sockets ports

由于某种原因,我得到以下异常(java.net.BindException:Address已在使用中),尽管我在使用它开始新套接字之前增加端口#。在使用线程之前,我没有发生此异常。

发件人应将文件的一部分(每个部分使用新套接字)发送给接收方。该程序正在运行,所有部分都是在不使用线程的情况下收到的。

现在只接收文件的第一部分,因为服务器在第一部分之后没有创建任何套接字。

此外,这些端口#s没有被使用,因为在我开始使用线程之前它们都工作了。

我是线程新手所以我知道我可能错了。

提前致谢!

服务器类:

public class Server {
int port = 8500;

public Server(int x) {
    for (int i = 0; i < x; i++) {
        ServerThread s = new ServerThread(port);
        s.start();
        port++;
    }

}

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

    DatagramSocket socket = new DatagramSocket(7499);
    byte[] buffer = new byte[256];
    DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
    socket.receive(receivePacket);
    String message = new String(buffer, 0, receivePacket.getLength());
    int xyz = Integer.parseInt(message);
    socket.close();
    Server server = new Server(xyz);

    try {
        FileJoin f = new FileJoin();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.exit(0);
}

} ServerThread类:

 public class ServerThread extends Thread {
private FileEvent fileEvent1 = null;
private int port;

ServerThread(int port) {

    this.port = port;
    run();
}

public void run() {
    try {
        createAndListenSocket(this.port);
    } catch (ClassNotFoundException | InterruptedException | IOException e) {

        e.printStackTrace();
    }
}

public void createAndListenSocket(int portx) throws InterruptedException,
        IOException, ClassNotFoundException {

    DatagramSocket socket1 = new DatagramSocket(portx);

    byte[] incomingData1 = new byte[1024 * 1000 * 50];

    DatagramPacket incomingPacket1 = new DatagramPacket(incomingData1,
            incomingData1.length);

    socket1.receive(incomingPacket1);

    byte[] data1 = incomingPacket1.getData();

    ByteArrayInputStream in1 = new ByteArrayInputStream(data1);

    ObjectInputStream is1 = new ObjectInputStream(in1);

    fileEvent1 = (FileEvent) is1.readObject();

    if (fileEvent1.getStatus(0).equalsIgnoreCase("Error")) {

        System.exit(0);

    }

    createAndWriteFile(); // writing the file to hard disk

    InetAddress IPAddress = incomingPacket1.getAddress();

    int porty = incomingPacket1.getPort();

    String reply = "The file was successfuly saved. ";

    byte[] replyBytea = reply.getBytes();

    DatagramPacket replyPacket =

    new DatagramPacket(replyBytea, replyBytea.length, IPAddress, porty);

    socket1.send(replyPacket);

    Thread.sleep(3000);

}

public void createAndWriteFile() {
    String outputFile1 = fileEvent1.getDestinationDirectory(0)
            + fileEvent1.getFilename(0);

    if (!new File(fileEvent1.getDestinationDirectory(0)).exists()) {

        new File(fileEvent1.getDestinationDirectory(0)).mkdirs();

    }

    File dstFile1 = new File(outputFile1);

    FileOutputStream fileOutputStream1 = null;

    try {

        fileOutputStream1 = new FileOutputStream(dstFile1);

        fileOutputStream1.write(fileEvent1.getFileData(0));

        fileOutputStream1.flush();

        fileOutputStream1.close();

        System.out.println("Output file : " + outputFile1
                + " is successfully saved ");

    } catch (FileNotFoundException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
}

}

客户类:

public class Client {

private FileEvent event1 = null;
private String sourceFilePath = "D:/workspace/newUDP/Image.jpgPart";
private int filenum;
private String destinationPath = "E:/UDPreceive/";
private int port = 8500;

private String hostName = "127.0.0.1";

public Client() {

}

public void createConnection(int x) {

    try {
        InetAddress IPAddress = InetAddress.getByName(hostName);
        for (int i = 0; i < x; i++) {
            DatagramSocket socket1 = new DatagramSocket();

            byte[] incomingData = new byte[1024];

            event1 = getFileEvent(0);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            ObjectOutputStream os = new ObjectOutputStream(outputStream);

            os.writeObject(event1);

            byte[] data = outputStream.toByteArray();

            DatagramPacket sendPacket1 = new DatagramPacket(data,
                    data.length, IPAddress, port);

            socket1.send(sendPacket1);

            System.out.println("File sent from client");

            DatagramPacket incomingPacket = new DatagramPacket(
                    incomingData, incomingData.length);

            socket1.receive(incomingPacket);

            String response = new String(incomingPacket.getData());

            System.out.println("Response from server:" + response);

            port++;
        }

        Thread.sleep(2000);

    } catch (UnknownHostException e) {

        e.printStackTrace();

    } catch (SocketException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    } catch (InterruptedException e) {

        e.printStackTrace();

    }

}

public FileEvent getFileEvent(int i) {

    FileEvent fileEvent = new FileEvent();
    sourceFilePath = sourceFilePath + filenum;

    String fileName1 = sourceFilePath.substring(
            sourceFilePath.lastIndexOf("/") + 1, sourceFilePath.length());

    String path1 = sourceFilePath.substring(0,
            sourceFilePath.lastIndexOf("/") + 1);

    fileEvent.setDestinationDirectory(destinationPath, 0);

    fileEvent.setFilename(fileName1, 0);

    fileEvent.setSourceDirectory(sourceFilePath, 0);

    File file1 = new File(sourceFilePath);
    filenum++;
    sourceFilePath = "D:/workspace/newUDP/Image.jpgPart";

    if (file1.isFile()) {

        try {

            DataInputStream diStream = new DataInputStream(
                    new FileInputStream(file1));

            long len = (int) file1.length();

            byte[] fileBytes = new byte[(int) len];

            int read = 0;

            int numRead = 0;

            while (read < fileBytes.length
                    && (numRead = diStream.read(fileBytes, read,

                    fileBytes.length - read)) >= 0) {

                read = read + numRead;

            }

            fileEvent.setFileSize(len, 0);

            fileEvent.setFileData(fileBytes, 0);

            fileEvent.setStatus("Success", 0);

        } catch (Exception e) {

            e.printStackTrace();

            fileEvent.setStatus("Error", 0);

        }

    } else {

        System.out.println("path specified is not pointing to a file");

        fileEvent.setStatus("Error", 0);

    }

    return fileEvent;

}

public static void main(String[] args) throws IOException {
    try {
        FileSplit f = new FileSplit();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        DatagramSocket socket = new DatagramSocket();
        String xyz = "" + FileSplit.getJ();
        System.out.println(xyz);
        InetAddress serverAddress = InetAddress.getByName("127.0.0.1");

        byte[] sendBytes = xyz.getBytes();

        DatagramPacket sendPacket = new DatagramPacket(sendBytes,
                sendBytes.length, serverAddress, 7499);
        socket.send(sendPacket);
        System.out.println(xyz);
        Client client = new Client();

        client.createConnection(Integer.parseInt(xyz));
    } catch (IOException x) {

    }

    System.exit(0);
}

} 堆栈跟踪:

java.net.BindException: Address already in use: Cannot bind
at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.bind0(Unknown Source)
at java.net.AbstractPlainDatagramSocketImpl.bind(Unknown Source)
at java.net.DatagramSocket.bind(Unknown Source)
at java.net.DatagramSocket.<init>(Unknown Source)
at java.net.DatagramSocket.<init>(Unknown Source)
at java.net.DatagramSocket.<init>(Unknown Source)
at pack.ServerThread.createAndListenSocket(ServerThread.java:32)
at pack.ServerThread.run(ServerThread.java:24)

1 个答案:

答案 0 :(得分:1)

  1. 你这里没有使用线程。你在构造函数中启动你的服务器。
  2. 当您致电s.start();时,您正在调用stub method of Thread,因为其运行方法具有不同的签名,您需要覆盖它,而不是重载它,请参阅差异here
  3. 其他软件也可以使用您的端口。你需要检查它是否免费,而不仅仅是使用它