Reputation: 3850
I'm trying to create a simple class that can is able to send files over a network. Basically, this class is created once on each machine, a separate listening thread is started, and it can send and receive files. At this point I've hard-coded the other addresses (to a loopback) and the file-locs in order to simplify testing.
Here's my class:
public class ConnectionHandler extends Thread{
private ServerSocket sSocket;
private Socket socket;
public ConnectionHandler(){
try {
this.sSocket = new ServerSocket(6533);
this.socket = new Socket("127.0.0.1", 6533);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
public void sendFile(File f) {
try {
int count;
byte[] buffer = new byte[1024];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
OutputStream out = socket.getOutputStream();
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
out.flush();
out.close();
in.close();
socket.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run(){
try {
int count;
byte[] buffer = new byte[1024];
InputStream in = sSocket.accept().getInputStream();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(location));
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
out.flush();
}
out.close();
in.close();
sSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
However, I'm running into a 'Address already in use' error and cannot figure out the issue within my code. Additionally, I recognize that my 'run' thread terminates after one transmission, this is intentional for testing. I plan on implementing a more robust thread that can handle multiple connections, etc.
Upvotes: 0
Views: 597
Reputation: 116918
However, I'm running into a 'Address already in use' error and cannot figure out the issue within my code
Any chance you are trying to fork multiple ConnectionHandler
threads? That would try to start multiple server sockets on more 6533 and the 2nd one would throw an exception.
Typically the main thread starts the server socket and a ConnectionHandler
is forked after a connection is accepted. Something like:
// main or server thread
ServerSocket serverSocket = new ServerSocket(6533);
try {
while (!shuttingDown) {
Socket socket = serverSocket.accept();
// better would be to use an ExecutorService thread-pool here
new Thread(new ConnectionHandlerRunnable(socket)).start();
}
} finally {
serverSocket.close();
}
Upvotes: 0
Reputation: 311039
Something else is listening to port 6533. netstat
will tell you what.
Upvotes: 1