gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:49:35 24 4
gpt4 key购买 nike

出于某种原因,我收到以下异常(java.net.BindException:地址已在使用中),尽管我在使用它启动新套接字之前增加了端口号。在使用线程之前我没有出现过这个异常。

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

现在,接收器仅接收文件的第一部分,因为服务器在第一个之后不会创建任何套接字。

此外,这些端口号未使用,因为在我开始使用线程之前它们都已工作。

我是线程新手,所以我知道我可能使用错误。

提前致谢!

服务器类别:

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

关于java - 使用不同端口号创建套接字时地址已被使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24336825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com