Last active
April 7, 2018 20:51
-
-
Save Bahaaib/12dff4fdb4ccf198d7d49da9c9cbc325 to your computer and use it in GitHub Desktop.
TCP Connection via Java Sockets /Server-Side implementaion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Created by Bahaa on 4/7/2018. | |
| */ | |
| package com.example.server; | |
| import java.net.*; | |
| import java.io.*; | |
| import java.util.Base64; | |
| public class Server { | |
| private static DataInputStream dataInputStream; | |
| private static DataOutputStream dataOutputStream; | |
| private static ServerSocket serverSocket; | |
| private static Socket socket; | |
| private static File mFile; | |
| private static FileInputStream fileInputStream; | |
| private static String imageDataToString; | |
| private static byte[] imageData; | |
| //TODO: Implement interrupt FLAG to close socket | |
| private boolean wasInterrupted; | |
| public static void main(String[] args) throws IOException { | |
| // Establishing Connection.. | |
| serverSocket = new ServerSocket(13267); | |
| //TODO: Replace the condition with interrupt FLAG | |
| while(true) { | |
| System.out.println("WAITING..."); | |
| socket = serverSocket.accept(); | |
| System.out.println("CONNECTION ADMITTED.."); | |
| System.out.println("CLIENT INFO: " + socket); | |
| dataInputStream = new DataInputStream(socket.getInputStream()); | |
| dataOutputStream = new DataOutputStream(socket.getOutputStream()); | |
| mFile = new File("D:\\helloworld.jpg"); | |
| System.out.println("SENDING..."); | |
| fileInputStream = new FileInputStream(mFile); | |
| imageData = new byte[(int) mFile.length()]; | |
| fileInputStream.read(imageData); | |
| //Encoding byteArray into Base64 String.. | |
| imageDataToString = encodeImageToString(imageData); | |
| System.out.println(imageDataToString.length()); | |
| System.out.println(imageDataToString); | |
| dataOutputStream.writeUTF(imageDataToString); | |
| System.out.println(String.valueOf(dataOutputStream.size())); | |
| dataOutputStream.flush(); | |
| } | |
| // sock.close(); //Socket never closed till future interrupt FLAG received from client | |
| } | |
| /* Using Java.Util Base64 Encoder NOT "Apache Common" to avoid dependency problems.. | |
| Android.Util Base64 Decoder can perfectly decode Java.Util Encodings, | |
| Unlike Apache common, Which uses different "Weired' Algorithm. | |
| Also: Apache Common Library causes several problems when used on Android API Level > 23 | |
| */ | |
| public static String encodeImageToString(byte[] imageByteArray) { | |
| return Base64.getEncoder().encodeToString(imageByteArray); | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment