I'm using these two java sources to exchange a file between 2 PC(linux and mac). The problem is showed only on Linux.
I'm using these 2 codes in a thread where i recall more times.
But i have this error: Address already in use (bind failed). I have searched on the web and on this forum that the problem is the TCP connection still active, so there is a function of the class Server Socket called setReuseAddress(true) which allows me to reuse the address. I call this function after the instantiation of ServerSocket but the problems persists. How can i resolve this problem?
[EDIT] Server
{
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;
}
}
EDIT Client
{
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;
}
}