This should be simple enough, but I am missing something here. I have two toy classes: (a) a server that expect connections and serves files; and (b) a client that requests a file and prints it out on the standard output.
Server code:
package lp2.tarefa4;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import static java.lang.String.format;
import java.net.ServerSocket;
import java.net.Socket;
public class ServidorWeb implements Runnable {
private final String dirName;
public ServidorWeb(String dirName) {
this.dirName = dirName;
}
public static void main(String[] args) {
ServidorWeb srv = new ServidorWeb(args[0]);
srv.run();
}
@Override
public void run() {
System.out.println("Server started. Waiting for connections...");
while (true) {
try {
ServerSocket server = new ServerSocket(48080);
Socket socket = server.accept();
proccessRequest(socket);
}
catch (IOException ex) {
System.err.println("!!! ERRO: " + ex.getMessage());
}
}
}
private void proccessRequest(Socket socket) throws IOException {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String fileName = in.readUTF();
File inputFile = new File(dirName, fileName);
String msg = format("Request: %s:%d [%s]",
socket.getInetAddress(),
socket.getPort(),
inputFile.getPath());
System.out.println(msg);
DataInputStream fin = new DataInputStream(new FileInputStream(inputFile));
String s = fin.readUTF();
while (s != null) {
out.writeUTF(s);
s = fin.readUTF();
}
in.close();
out.close();
fin.close();
}
}
Client code:
package lp2.tarefa4;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class ClienteWeb implements Runnable {
private final String host;
private final int port;
private final String fileName;
public ClienteWeb(String host, int port, String fileName) {
this.host = host;
this.port = port;
this.fileName = fileName;
}
public static void main(String[] args) {
ClienteWeb srv = new ClienteWeb(args[0], Integer.parseInt(args[1]), args[2]);
srv.run();
}
@Override
public void run() {
try {
Socket socket = new Socket(host, port);
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF(fileName);
String s = in.readUTF();
while (s != null) {
System.out.println(s);
s = in.readUTF();
}
in.close();
out.close();
socket.close();
}
catch (IOException ex) {
System.err.println("!!! ERRO: " + ex.getMessage());
}
}
}
I am trying to run both, server and client, on the same machine, but every time I try to run the client always get this message from the server:
!!! ERRO: Address already in use (Bind failed)
Do I have to do anything different than the above to run this code without errors?
Thanks.