我正在使用这两个java源在2台PC(linux和mac)之间交换文件。 该问题仅在Linux上显示。
我在一个线程中使用这两个代码,我记得更多次。
但我有这个错误:地址已在使用中(绑定失败)。 我在网上和这个论坛上搜索过问题是TCP连接仍处于活动状态,因此有一个名为 setReuseAddress(true)的服务器套接字的功能,它允许我重用该地址。我在ServerSocket实例化后调用此函数但问题仍然存在。 我该如何解决这个问题?
[编辑] 服务器
{
final int SOCKET_PORT = 13267;
final String FILE_TO_SEND = "/Users/jo/Desktop/cryptedSymmetric.key";
boolean flag = true;
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(); // create unbound ServerSocket
servsock.setReuseAddress(true);
servsock.bind(new InetSocketAddress(SOCKET_PORT));
// while (flag) {
System.out.println("SO_REUSEADDRESS is enabled: " + servsock.getReuseAddress());
System.out.println("Waiting client B...");
try {
sock = servsock.accept();
System.out.println("Connection : " + sock);
// send file
File myFile = new File(FILE_TO_SEND);
byte[] mybytearray = new byte[(int) myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
os = sock.getOutputStream();
System.out.println("Invio del file " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
System.out.println("Done.");
flag = false;
} finally {
if (bis != null)
bis.close();
if (os != null)
os.close();
if (sock != null)
sock.close();
}
// }
} finally {
if (servsock != null)
servsock.close();
return flag;
}
}
编辑客户
{
int SOCKET_PORT = 0;
SOCKET_PORT = 13267;
// final String SERVER = "192.168.1.2";
final String FILE_TO_RECEIVED = "/Users/jo/Desktop/publicB.key";
final int FILE_SIZE = 6022386;
boolean flag = true;
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(address.getHostAddress(), SOCKET_PORT);
System.out.println("Connessione...");
// receive file
byte[] mybytearray = new byte[FILE_SIZE];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
// bytesRead = is.read(mybytearray, 0, mybytearray.length);
// current = bytesRead;
int count;
while ((count = is.read(mybytearray)) > 0) {
bos.write(mybytearray, 0, count);
}
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED + " scaricato (" + current + " bytes letti)");
flag = false;
} finally {
if (fos != null)
fos.close();
if (bos != null)
bos.close();
if (sock != null)
sock.close();
return flag;
}
}
答案 0 :(得分:1)
我在ServerSocket实例化后调用此函数但问题仍然存在。
那是因为你打电话太晚了。你应该已经注意到在调用之前抛出了异常。您需要将创建与绑定分开:
servsock = new ServerSocket(); // create unbound ServerSocket
servsock.setReuseAddress(true);
servsock.bind(new InetSocketAddress(SOCKET_PORT));
请注意,您的复制代码在两端应该相同,而不是您使用的任何一个版本,它们会出现各种问题和谬误:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}