Skip to content

Commit

Permalink
Encapsulated socket handling for Media Server/Client. MediaServer and…
Browse files Browse the repository at this point in the history
… MediaClient now ready for LAN testing
  • Loading branch information
ThePurpleJedi committed Feb 21, 2022
1 parent ed277c5 commit b655e0e
Show file tree
Hide file tree
Showing 13 changed files with 312 additions and 263 deletions.
12 changes: 11 additions & 1 deletion .idea/sonarlint/issuestore/index.pb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

50 changes: 50 additions & 0 deletions src/com/mercurys/almostfinished/ClientSocketHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.mercurys.almostfinished;

import com.mercurys.threads.ReadMediaThread;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientSocketHandler {

private Socket socket;
private DataOutputStream outputStream;
private ReadMediaThread incomingReaderThread;
private MessageSender messageSender;

public ClientSocketHandler(String address, int port) throws IOException {
connectToServer(address, port);
initialiseIO();
}

private void connectToServer(String address, int port) throws IOException {
this.socket = new Socket(address, port);
System.out.println("Connected to server! [" + this.socket.getRemoteSocketAddress() + "]");
}

private void initialiseIO() throws IOException {
this.outputStream = new DataOutputStream(this.socket.getOutputStream());
PrintWriter writer = new PrintWriter(this.outputStream, true);
messageSender = new MessageSender(new Scanner(System.in), writer, outputStream);
}

public void talkToServer() throws IOException {
initialiseReaderThread();
messageSender.sendMessagesToOtherUser();
closeConnection();
}

private void initialiseReaderThread() throws IOException {
incomingReaderThread = new ReadMediaThread(this.socket.getInputStream(),
"M_Host");
incomingReaderThread.start();
}

private void closeConnection() throws IOException {
incomingReaderThread.exitThread();
this.socket.close();
this.outputStream.close();
System.out.println("Closing connection... Goodbye!");
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.mercurys.unfinished;
package com.mercurys.almostfinished;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
Expand All @@ -22,54 +22,75 @@ public ImageHandler(DataInputStream inputStream) {
this.inputStream = inputStream;
}

public ImageHandler() {
}

public void sendImageFileAsByteStream(final String imageFileName) throws IOException {
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final BufferedImage bufferedImage = ImageIO.read(new File(imageFileName));
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);

final byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
writeImageToOutputStream(byteArrayOutputStream, bufferedImage);
}

private void writeImageToOutputStream(ByteArrayOutputStream byteArrayOutputStream, BufferedImage bufferedImage) throws IOException {
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
final byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
this.outputStream.write(size);
this.outputStream.write(byteArrayOutputStream.toByteArray());
}

public BufferedImage getImageAsBufferedImage() {
try {
final byte[] imgSize = new byte[4];
this.inputStream.readFully(imgSize);
final byte[] imgArr = new byte[ByteBuffer.wrap(imgSize).asIntBuffer().get()];
this.inputStream.readFully(imgArr);
return ImageIO.read(new ByteArrayInputStream(imgArr));

return ImageIO.read(new ByteArrayInputStream(getImageAsBytes()));
} catch (final IOException e) {
System.out.println("Exception Occurred!");
e.printStackTrace();
return null;
}
}

private byte[] getImageAsBytes() throws IOException {
return readImageSize(ByteBuffer.wrap(readImageSize(4)).asIntBuffer().get());
}

private byte[] readImageSize(int x) throws IOException {
final byte[] imgSize = new byte[x];
this.inputStream.readFully(imgSize);
return imgSize;
}

public void downloadBufferedImage(final BufferedImage image) {
if (image == null) {
return;
}
final String s = System.getProperty("file.separator");
final String downloadPath =
MessageFormat.format("{0}{1}Pictures{1}Mercurys{1}{3}{1}ReceivedImage{2}.png",
System.getProperty("user.home"), s, new SimpleDateFormat("HHmmss")
.format(Calendar.getInstance().getTime()), new SimpleDateFormat("dd.MM.yyyy")
.format(Calendar.getInstance().getTime()));
setDownloadPath();
writeImageToDownloadLocation(image);
}

private void writeImageToDownloadLocation(BufferedImage image) {
try {
Files.createDirectories(Paths.get(downloadPath.substring(0, downloadPath.lastIndexOf(s)) + s));
ImageIO.write(image, "png", new File(downloadPath));
this.imageDownloadPath = downloadPath;
} catch (final IOException e) {
createDirectoriesToDownloadLocation();
ImageIO.write(image, "png", new File(imageDownloadPath));
} catch (IOException e) {
e.printStackTrace();
}
}

private void createDirectoriesToDownloadLocation() throws IOException {
String s = System.getProperty("file.separator");
Files.createDirectories(Paths.get(
imageDownloadPath.substring(0, imageDownloadPath.lastIndexOf(s)) + s));
}

private void setDownloadPath() {
final String s = System.getProperty("file.separator");
imageDownloadPath =
MessageFormat.format("{0}{1}Pictures{1}Mercurys{1}{3}{1}ReceivedImage{2}.png",
System.getProperty("user.home"), s, getFormattedSimpleDate("HHmmss"),
getFormattedSimpleDate("dd.MM.yyyy"));
}

private String getFormattedSimpleDate(String format) {
return new SimpleDateFormat(format)
.format(Calendar.getInstance().getTime());
}

public String getImageDownloadPath() {
return imageDownloadPath;
}
Expand Down
40 changes: 40 additions & 0 deletions src/com/mercurys/almostfinished/MediaClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.mercurys.almostfinished;

import java.io.IOException;
import java.util.Scanner;

public class MediaClient {

ClientSocketHandler clientSocketHandler;

private MediaClient(final String address, final int port) {
try {
clientSocketHandler = new ClientSocketHandler(address, port);
} catch (final IOException u) {
u.printStackTrace();
}
}

public static void main(final String[] args) {
final MediaClient client = new MediaClient(getHostAddress(), 4444);
client.startTalking();
System.out.println("Thank you for using Project Mercurys!");
}

private static String getHostAddress() {
final Scanner sc = new Scanner(System.in);
System.out.println("Enter server host address [IP] or press 1 for localhost:");
final String hostAddress = sc.next();
return (hostAddress.equals("1"))? "192.168.0.151" : hostAddress;
}

private void startTalking() {
try {
clientSocketHandler.talkToServer();
} catch (final IOException e) {
e.printStackTrace();
}
}


}
33 changes: 33 additions & 0 deletions src/com/mercurys/almostfinished/MediaServer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.mercurys.almostfinished;

import java.io.IOException;

public class MediaServer {

private ServerSocketHandler serverSocketHandler;

private MediaServer(final int port) {
try {
serverSocketHandler = new ServerSocketHandler(port);
} catch (final IOException e) {
System.out.println("Exception occurred!");
e.printStackTrace();
}
}

public static void main(final String[] args) {
final MediaServer mediaServer = new MediaServer(4444);
mediaServer.startTalking();
System.out.println("Thank you for using Project Mercurys!");
}

private void startTalking() {
try {
serverSocketHandler.talkToClient();
} catch (final IOException e) {
e.printStackTrace();
}
}


}
42 changes: 42 additions & 0 deletions src/com/mercurys/almostfinished/MessageSender.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.mercurys.almostfinished;

import com.mercurys.encryption.Encryption;

import java.io.*;
import java.util.Scanner;

public class MessageSender {
private final Scanner scanner;
private final Encryption encryption = new Encryption();
private final PrintWriter writer;
private final DataOutputStream outputStream;

public MessageSender(Scanner scanner, PrintWriter writer, DataOutputStream outputStream) {
this.scanner = scanner;
this.writer = writer;
this.outputStream = outputStream;
}

public void sendMessagesToOtherUser() throws IOException {
String outGoingLine;
while (!(outGoingLine = scanner.nextLine()).equals("-x-")) {
sendMessage(outGoingLine);
}
writer.println(new Encryption().encrypt("Connection closed by server."));
}

public void sendMessage(String outGoingLine) throws IOException {
if (outGoingLine.startsWith("/image")) {
this.handleImageUpload(outGoingLine.substring(7));
} else {
writer.println(encryption.encrypt(outGoingLine));
}
}

public void handleImageUpload(final String imageFileName) throws IOException {
ImageHandler imageHandler = new ImageHandler(outputStream);
writer.println(new Encryption().encrypt("/image incoming!"));
imageHandler.sendImageFileAsByteStream(imageFileName);
System.out.println("[M. Console]: Image sent!");
}
}
61 changes: 61 additions & 0 deletions src/com/mercurys/almostfinished/ServerSocketHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.mercurys.almostfinished;

import com.mercurys.threads.ReadMediaThread;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ServerSocketHandler {

private final ServerSocket serverSocket;
private Socket socket;
private DataOutputStream outputStream;
private MessageSender messageSender;
private ReadMediaThread incomingReaderThread;

public ServerSocketHandler(int serverPort) throws IOException {
serverSocket = new ServerSocket();
initialiseServerSocket(serverPort);
acceptClientRequest();
initialiseIO();
}

private void initialiseServerSocket(int serverPort) throws IOException {
String hostAddress = "192.168.0.151"; //replace with one's own LAN IP address
serverSocket.bind(new InetSocketAddress(hostAddress, serverPort));
System.out.println("""
Server initiated.
Waiting for client...""");
}

private void acceptClientRequest() throws IOException {
this.socket = serverSocket.accept();
System.out.println("Client accepted!");
}

private void initialiseIO() throws IOException {
this.outputStream = new DataOutputStream(this.socket.getOutputStream());
PrintWriter writer = new PrintWriter(this.outputStream, true);
messageSender = new MessageSender(new Scanner(System.in), writer, outputStream);
}

public void talkToClient() throws IOException {
initialiseReaderThread();
messageSender.sendMessagesToOtherUser();
closeConnection();
}

private void initialiseReaderThread() throws IOException {
incomingReaderThread = new ReadMediaThread(this.socket.getInputStream(),
"M_Client");
incomingReaderThread.start();
}

private void closeConnection() throws IOException {
incomingReaderThread.exitThread();
this.socket.close();
this.outputStream.close();
System.out.println("Closing connection... Goodbye!");
}
}
2 changes: 1 addition & 1 deletion src/com/mercurys/encryption/Decryption.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public Decryption() {

public String decrypt(final String message) {
if (message == null) {
return null;
return "";
}
String[] messageAsWords = message.split(" +");
messageAsWords = preProcessTheMessage(messageAsWords);
Expand Down
Loading

0 comments on commit b655e0e

Please sign in to comment.