Using raw and raw socket, this question deals with 4 points:
reading file
written in socket
server socket opening
reading a server socket
NOTE : For simplicity and brevity I am not using buffered streams ; do not do this in production code without knowing very well that you do not want to use buffered streams , as they usually help a lot in the performance of read and write operations.
File reading
To start, we need a way. I'll call path
, assuming it's a variable that will be filled correctly. To open the file for reading, we use FileInputStream
. To read the first 255 bytes of a file, we can do this:
InputStream in = new FileInputStream(path);
byte[] buffer = new byte[255];
int readBytes = in.read(buffer);
in.close();
To not forget to close the feature, we can use AutoCloseable and try-with-recources
:
try (InputStream in = new FileInputStream(path)) {
byte[] buffer = new byte[255];
int readBytes = in.read(buffer);
}
Writing in socket
To write to the socket, we need to open a socket and get its OutpuStream
. To open the socket, get the stream and write "any string", we can do so (Documentation :
try (
Socket bareSocket = new Socket(hostName, portNumber);
OutputStream out = bareSocket.getOutputStream();
) {
out.write("uma string qualquer".getBytes());
}
Note that it is always necessary to close everything, so I put everything in a block try-with-resources
.
Then, with OutputStream
open, we need to write everything that is read from InputStream
of file to OutputStream
of socket. The Apache folks have already solved this problem for folks with IOUtils.copy
. So, writing on the socket with the contents of the file would look like this:
try (
Socket bareSocket = new Socket(hostName, portNumber);
OutputStream out = bareSocket.getOutputStream();
InputStream in = new FileInputStream(path)
) {
IOUtils.copy(in, out);
}
Server socket opening
Oracle itself provides a code sample using ServerSocket
: link
There are no secrets here, just create a ServerSocket
object using a port and, when it receives a connection call, get the socket generated with accept()
. Something like this, for a% informed%:
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
InputStream in = clientSocket.getInputStream();
) {
// abri a conexão, agora faça coisas...
}
Reading a server socket
Since we already have portNumber
, we can usually use it as another InputStream
any. For example, if you want to write the image to the file in InputStream
path, do so:
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
InputStream in = clientSocket.getInputStream();
OutputStream out = new FileOutputStream(pathDestino, false);
) {
IOUtils.copy(in, out);
}