How to implement thread in succession - java

I would like to implement a transfer with socket for transfering pictures and check on the server if the picture is ever loaded and if it is true not transfering the picture simply change the imageView.
I have a client and a server which work for simply transfer picture between 2 devices. But i want to send a hash of each pictures once at each time before send them. My dificulty is primarily on the thread manager, i have implement a listener for the 1st thread (send / receive picture's hash on client / server) to know when it's finished and then start the second thread (send / receive pictures on client / server). But i don't know if my methodology is ok because it doesn't work well (the server receive the hash on the start but not the other).
I hope that i am clear, here is my parts of code concerned, thanks to someone who can give me a solution.
Server
private class ReceiverHash extends Thread {
private List<TaskListener> listeners = new ArrayList<TaskListener>();
public void addListener(TaskListener listener) {
listeners.add(listener);
}
void getTaskState(Boolean state) {
for (TaskListener listener : listeners) {
listener.getTaskState(state);
}
}
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(socketServerPORT);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while (true) {
String str = br.readLine(); // lecture du message
if (str.equals("END")) {
serverSocket.close();
getTaskState(true);
break;
}
hashList.add(str);
Log.d("HASH_RECEIVER_LOG", str); // Log debug hash
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class Receiver extends Thread {
int pos = 0;
int cmpt = 0;
#Override
public void run() {
// create ServerSocket using specified port
try {
ServerSocket serverSocket = new ServerSocket(socketServerPORT);
while (true) {
//checkFileExist();
File f = new File(getFilesDir(), "img" + Integer.toString(pos) + ".png");
fileList.add(f);
Log.d("HASH_RECEIVER_LOG", "Attente d'une réponse du client");
Socket socket = serverSocket.accept();
Log.d("HASH_RECEIVER_LOG", "Reception d'une réponse");
f.createNewFile();
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = new FileOutputStream(f);
byte[] bytes = new byte[2 * 1024];
int count;
while ((count = inputStream.read(bytes)) > 0) {
Log.d("RECEIVER_CMPT", Integer.toString(cmpt));
outputStream.write(bytes, 0, count);
cmpt = cmpt + count;
}
myBitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
runOnUiThread(new Runnable() {
#Override
public void run() {
imgDiapo.setImageBitmap(myBitmap);
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
How i use listener on the activity :
ReceiverHash receiverHash = new ReceiverHash();
receiverHash.start();
receiverHash.addListener(this);
Client
public class Sender extends AsyncTask<Void, Void, Void> {
private String dstAddress;
private int dstPort;
private String fPath;
public Sender(String address, int port, String path) {
dstAddress = address;
dstPort = port;
fPath = path;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
FileInputStream inputStreamSend = new FileInputStream(fPath);
OutputStream outputStreamSend = socket.getOutputStream();
byte[] buffer = new byte[2 * 1024];
int count;
while ((count = inputStreamSend.read(buffer)) > 0) {
outputStreamSend.write(buffer, 0, count);
}
outputStreamSend.close();
inputStreamSend.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public class HashSender extends AsyncTask<Void, Void, Void> {
private String dstAddress;
private int dstPort;
String hash;
//private ArrayList <String> listHash;
private List<TaskListener> listeners = new ArrayList<TaskListener>();
public HashSender(String address, int port, String path) throws IOException, NoSuchAlgorithmException {
dstAddress = address;
dstPort = port;
hash = sha1(new File(path)); //methode encryption in sha1
}
public void addListener(TaskListener listener) {
listeners.add(listener);
}
void getTaskState(Boolean state) {
for (TaskListener listener : listeners) {
listener.getTaskState(state);
}
}
#Override
protected void onPostExecute(Void v) {
getTaskState(true);
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
OutputStream outputStreamSend = socket.getOutputStream();
BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(outputStreamSend));
buf.write(hash);
buf.newLine();
buf.flush();
Log.d("toto", hash);
buf.write("END");
buf.newLine();
buf.flush();
outputStreamSend.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
How i use listener on the activity :
HashSender hashSender = new HashSender(dstAddress.get(i), dstPort, selectedItemPath.get(pos));
hashSender.addListener(ControlsActivity.this);
hashSender.execute();

Related

JAVA Socket object + text

Does it possible, to get from client and
objetObjectInputStream
and
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
for example, some client send me tet message, and someone send files. Should I make a new socket server for each?
public class ServerRequests {
Connection con = new Connection();
private Socket socket;
private BufferedReader in;
private BufferedWriter out;
public ServerRequests(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
run();
}
public void run() {
String word;
try {
String object;
ObjectInputStream obIn = new ObjectInputStream(socket.getInputStream());
while ((object = (String) obIn.readObject()) != null){
if (object.contains("F47S")){
String[] result = object.split(":");
String fileName = result[1];
String url = result[2];
String culture = result[3];
System.out.println("FileName:" +fileName);
System.out.println("url:" +url);
FileOutputStream outOb = null;
if(culture.contains("test")) {
outOb = new FileOutputStream(fileName);
}
DataInputStream inOb = new DataInputStream(socket.getInputStream());
byte[] bytes = new byte[5*1024];
int count, total=0;
long lenght = inOb.readLong();
while ((count = inOb.read(bytes)) > -1) {
total+=count;
outOb.write(bytes, 0, count);
if (total==lenght) break;
}
outOb.close();
}
}
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// while (true) {
word = in.readLine();
System.out.println(word);
if (word != null) {
String[] result = word.split(":");
String type = result[0];
if (type.contains("AUTH")) {
String login = result[2];
String pass = result[4];
String gui = con.checkLogin(pass, login);
auth(gui);
}
} catch (IOException e) {
}
}
private void auth(String gui) {
try {
out.write(gui + "\n");
out.flush();
} catch (IOException ignored) {
}
}
private void success(String status) {
try {
out.write(status+ "\n");
out.flush();
} catch (IOException ignored) {
}
}
}

android.os.NetworkOnMainThreadException but my class extends Thread

I have a client class that extends Thread to start socket programming
my class code
class MyClientMessages extends Thread {
Socket socket;
int PORT = 5002;
DataInputStream din;
DataOutputStream dout;
public MyClientMessages(String IP) {
try {
System.out.println("IP = ======= " + IP + " TYPE = " + TYPE);
//*********** crash here ***************
socket = new Socket(IP,PORT); // *********** it crash here *************
din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
this.start();
}catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
byte[] data = new byte[1024];
int size = 0;
try {
while ((size = din.read(data)) > 0) {
final String str = new String(data,"UTF8");
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = new TextView(ServerChat.this);
textView.setTextSize(15);
textView.setText(str);
linearLayout.addView(textView);
}
});
}
}catch (IOException e) {
e.printStackTrace();
try {
dout.close();
din.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public void WriteToSocket(byte[] arr,int size) {
try {
dout.write(arr,0,size);
dout.flush();
}catch (IOException e) {
e.printStackTrace();
try {
dout.close();
din.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I make this class inside my activity class. I have another class inside my activity class for server, which extends thread and it works fine. Why does this client class crash and give me this error ?
this how I use it on my onCreate() function:
if (TYPE == 1) {
serverMessages = new MyServerMessages(5002);
Toast.makeText(this,"Room Started Wait clients To Join",Toast.LENGTH_LONG).show();
}
else {
clientMessages = new MyClientMessages(deConvert(mycode)); // crash here
Toast.makeText(this,"Connect To Room",Toast.LENGTH_LONG).show();
}
why this client class crash and give me this error ?
Because you are creating a Socket and opening it in the constructor. Move that logic into run().

Sending a binary file over a Java Socket

I have written a multi-client TCP server that has the dual purpose of sending Json (text based) command strings and also sending an SQLite database file to multiple clients. Everything is working nicely except... the database file uses the special character hex81 (decimal 129) for some internal purpose. When I read the database file into a byte array, Java converts this character to decimal -127 because of Java's signed representation of bytes. However the socket is actually transmitting this character as hex3F. So when I receive the save the data in the client and save it to a file, the database is corrupt due to the presence of h3F chars instead of h81.
Why is this happening and how do I correct it?
Here is the complete code that I am using for the server (a new instance of this class is started by a separate TCPServer class whenever a client connects):
public class TCPServerThread extends Thread {
// Connect status constants
private final static int NULL = 0;
private final static int DISCONNECTED = 1;
private final static int DISCONNECTING = 2;
private final static int BEGIN_CONNECT = 3;
private final static int CONNECTED = 4;
private final static String END_SESSION = new Character((char)0).toString(); // Indicates the end of a session
// Connection state info
private int connectionStatus = DISCONNECTED;
private static StringBuffer txBuffer = new StringBuffer("");
private static ByteArrayOutputStream txBuffer2 = new ByteArrayOutputStream();
private static File file;
// TCP Components
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private DataOutputStream out2 = null;
private String s = "";
private DecodeJson dj = new DecodeJson();
private boolean doRun;
public TCPServerThread(Socket socket) throws IOException {
doRun = true;
clientSocket = socket;
changeStatusTS(BEGIN_CONNECT, true);
}
public void run() {
while (doRun) {
try { // run every ~10 ms
Thread.sleep(10);
}
catch (InterruptedException e) {}
if (Mainscreen.shutdown == true || TCPClient.close == true)
connectionStatus = DISCONNECTING;
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out2 = new DataOutputStream(clientSocket.getOutputStream());
TCPServer.writers.add(out); // add this socket to the connected clients list
changeStatusTS(CONNECTED, true);
}
// If error, clean up and output an error message
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Send data
if (txBuffer.length() != 0) {
for (PrintWriter writer : TCPServer.writers) {
writer.print(txBuffer);
writer.flush();
if(writer.checkError()) {
closeSocket();
changeStatusTS(DISCONNECTING, true);
}else {
changeStatusTS(NULL, true);
}
}
txBuffer.setLength(0);
}
if (txBuffer2.size() != 0) {
byte[] result = txBuffer2.toByteArray();
System.out.println(result[745] + "," + result[746] + "," + result[747] + "," + result[748] + "," + result[749] + "," + result[750]);
out2.write(result);
out2.flush();
txBuffer2.reset();
}
// Receive data
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
// Check if it is the end of a transmission
if (s.equals(END_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Otherwise, receive text
else {
dj.receiveString(s);
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
System.out.println("Socket error " + e);
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
// Tell clients to disconnect as well
if (out != null) {
out.print(END_SESSION);
out.flush();
}
// Clean up (close all streams/sockets)
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
// Add command to text send-buffer
public static void sendString(String s) {
synchronized (txBuffer) {
txBuffer.append(s + "\n");
}
}
// Add file data to binary send buffer
public static void sendFile(String filename) {
synchronized (txBuffer2) {
file = new File(filename);
byte[] content = new byte[(int)file.length()];
FileInputStream fin;
try {
fin = new FileInputStream(file);
fin.read(content);
System.out.println(content[745] + "," + content[746] + "," +content[747] + "," +content[748] + "," + content[749] + "," + content[750]);
txBuffer2.write(content);
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
f.printStackTrace();
}
}
}
private void changeStatusTS(int newConnectStatus, boolean noError) {
// Change state if valid state
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
}
private void closeSocket(){
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
}
// Cleanup for disconnect
private void cleanUp() {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
}
catch (IOException e) { serverSocket = null; }
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) { in = null; }
if (out != null) {
TCPServer.writers.remove(out); // remove this socket for the connected sockets list
out.close();
out = null;
}
doRun = false;
}
}
So as EJP suggested, the problem is due to using readers and writers.
The following code now works as expected (thanks for the tip EJP). I will get around to addressing the issue raised by VGR about wrapping client.getOutputStream() in both a PrintWriter and a BufferedOutputStream, but for now the code works nicely (this is a work in progress).
public class TCPServerThread extends Thread {
// Connect status constants
private final static int NULL = 0;
private final static int DISCONNECTED = 1;
private final static int DISCONNECTING = 2;
private final static int BEGIN_CONNECT = 3;
private final static int CONNECTED = 4;
private final static String END_SESSION = new Character((char)0).toString(); // Indicates the end of a session
// Connection state info
private int connectionStatus = DISCONNECTED;
private static StringBuffer txBuffer = new StringBuffer("");
private static BufferedOutputStream out2 = null;
private static File file;
// TCP Components
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private static BufferedInputStream fileData = null;
private String s = "";
private DecodeJson dj = new DecodeJson();
private boolean doRun;
public TCPServerThread(Socket socket) throws IOException {
doRun = true;
clientSocket = socket;
changeStatusTS(BEGIN_CONNECT, true);
}
public void run() {
while (doRun) {
try { // run every ~10 ms
Thread.sleep(10);
}
catch (InterruptedException e) {}
if (Mainscreen.shutdown == true || TCPClient.close == true)
connectionStatus = DISCONNECTING;
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out2 = new BufferedOutputStream(clientSocket.getOutputStream());
TCPServer.writers.add(out); // add this socket to the connected clients list
changeStatusTS(CONNECTED, true);
}
// If error, clean up and output an error message
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Send data
if (txBuffer.length() != 0) {
for (PrintWriter writer : TCPServer.writers) {
writer.print(txBuffer);
writer.flush();
if(writer.checkError()) {
closeSocket();
changeStatusTS(DISCONNECTING, true);
}else {
changeStatusTS(NULL, true);
}
}
txBuffer.setLength(0);
}
if (fileData != null) {
byte[] buffer = new byte[(int) file.length()];
for (int read = fileData.read(buffer); read >=0; read = fileData.read(buffer)) out2.write(buffer, 0, read);
out2.flush();
fileData = null;
}
// Receive data
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
// Check if it is the end of a transmission
if (s.equals(END_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Otherwise, receive text
else {
dj.receiveString(s);
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
System.out.println("Socket error " + e);
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
// Tell clients to disconnect as well
if (out != null) {
out.print(END_SESSION);
out.flush();
}
// Clean up (close all streams/sockets)
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
// Add command to text send-buffer
public static void sendString(String s) {
synchronized (txBuffer) {
txBuffer.append(s + "\n");
}
}
// Add file data to binary send buffer
public static void sendFile(String filename) {
file = new File(filename);
try {
fileData = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void changeStatusTS(int newConnectStatus, boolean noError) {
// Change state if valid state
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
}
private void closeSocket(){
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
}
// Cleanup for disconnect
private void cleanUp() {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
}
catch (IOException e) { serverSocket = null; }
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) { in = null; }
if (out != null) {
TCPServer.writers.remove(out); // remove this socket for the connected sockets list
out.close();
out = null;
}
doRun = false;
}
}

Android Lag in udp transmission

I have a problem with lag in udp transmission (over a local wifi network). The host sends data to all clients using UdpSender at 50Hz :
UDPSender:
public class UDPSender {
private DatagramSocket socket;
private DatagramPacket packet;
private ByteBuffer bb;
private InetAddress targetAddress;
private byte[] bytearray;
public UDPSender(int port,String targetAddress){
try {
this.targetAddress = InetAddress.getByName(targetAddress);
} catch (UnknownHostException e) {
}
try {
socket = new DatagramSocket();
} catch (IOException e) {
}
bb = ByteBuffer.allocate(169);
bytearray = bb.array();
packet = new DatagramPacket(bytearray, bytearray.length, this.targetAddress, port);
}
public void sendSignal(/*args*/){
if(!socket.isClosed()){
bb.putInt(pos, ...) //fill 'bb' with data from args
...
bytearray = bb.array();
packet.setData(bytearray);
try {
socket.send(packet);
} catch (IOException e) {
}
}
}
public void close(){
socket.close();
}
}
UDPReceiver:
public class UDPReceiver {
private DatagramSocket socket;
private DatagramPacket packet;
private byte[] packetDataBuffer = new byte[169];
private UDPSignalListener listener = null;
private ByteBuffer bb;
private String hostAddress;
private boolean isOpen = false;
private byte buffer;
private short bytes;
public UDPReceiver(int port, String hostAddress, UDPSignalListener listener){
try {
socket = new DatagramSocket(port);
} catch (IOException e) {
if(listener!=null)
listener.errorOpeningSocket(port);
}
packet = new DatagramPacket(packetDataBuffer, packetDataBuffer.length);
this.hostAddress = hostAddress;
this.listener = listener;
isOpen = true;
Thread t = new Thread(new Runnable(){
#Override
public void run() {
listen();
}
});
t.setDaemon(true);
t.start();
}
public void start(String hostAddress){
this.hostAddress = hostAddress;
isOpen = true;
Thread t = new Thread(new Runnable(){
#Override
public void run() {
listen();
}
});
t.setDaemon(true);
t.start();
}
private void listen(){
while(isOpen){
try {
socket.receive(packet);
} catch (IOException e) {
continue;
}
if(!isOpen)
return;
if(packet.getAddress().getHostAddress().equals(hostAddress)){
bb = ByteBuffer.wrap(packetDataBuffer);
//read data from bb
if(listener!=null)
listener.onSignalRecieved(/*pass data to program*/);
}
}
}
public int getPort(){
return socket.getLocalPort();
}
public void close(){
isOpen = false;
socket.close();
}
}
MainThread on host-side:
mainThread = new Thread(new Runnable(){
public void run(){
while(isMainLoopRunning){
...
for(int i=0;i<udpSender.length/*max 5*/;++i)
udpSender[i].sendSignal(...); //~50fps constantly //send data to client i
...
}
}
});
the client side gets the data via UDPSignalListener.onSignalReceived() (should be called every 20ms (50fps)). The data is saved and is used in the client's mainThread (which also runs at 50fps constantly). Unfortunately there is sometimes a lag (a delay up to 1 second), i.e onSignalReceived is not called every 20ms constantly. What could be the reason for the lag?

Saving mp3 file to client?

I'm trying to save a mp3 file from the server to the client and play it after that. I am loading the playlist and after that trying to play a song(The song is supposed to be saved on the client PC and played after that). I am building the application with JavaFXpackage main;
Controller class:
public class AudioController {
#FXML
private ResourceBundle resources;
#FXML
private URL location;
#FXML
private Button nextButton;
#FXML
private Button playButton;
#FXML
private ListView<String> playlist;
#FXML
private Button previousButton;
#FXML
private Button stopButton;
#FXML
void initialize() {
final AudioClient audioClient = new AudioClient("127.0.0.1", 3000);
audioClient.setUpConnection();
ArrayList<String> songList = audioClient.getPlaylist();
ObservableList<String> songs = FXCollections
.observableArrayList(songList);
playlist.setItems(songs);
playButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
String songToPlay = playlist.getSelectionModel()
.getSelectedItem();
if (songToPlay != null) {
try {
String linkToSong = audioClient.getSong(songToPlay);
Media song = new Media(linkToSong);
MediaPlayer mediaPlayer = new MediaPlayer(song);
mediaPlayer.play();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
}
Client class
public class AudioClient {
protected BufferedReader socketReader;
protected PrintWriter socketWriter;
protected InputStream is;
protected String hostIP;
protected int hostPort;
public AudioClient(String hostIP, int hostPort) {
this.hostIP = hostIP;
this.hostPort = hostPort;
}
public ArrayList<String> getPlaylist() {
ArrayList<String> fileLines = new ArrayList<String>();
try {
socketWriter.println("Playlist");
socketWriter.flush();
String line = null;
while ((line = socketReader.readLine()) != null) {
fileLines.add(line);
}
} catch (IOException e) {
System.out.println("There was a problem reading");
}
return fileLines;
}
public String getSong(String songName) throws IOException {
socketWriter.println("Request " + songName);
socketWriter.flush();
String filePath = new String("D:\\" + songName + ".mp3");
FileOutputStream fos = new FileOutputStream(new File(filePath));
BufferedOutputStream bos = new BufferedOutputStream(fos);
int count;
byte[] buffer = new byte[4096];
while ((count = is.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, count);
}
return filePath;
}
public void setUpConnection() {
try {
Socket client = new Socket(hostIP, hostPort);
socketReader = new BufferedReader(new InputStreamReader(
client.getInputStream()));
InputStream is = client.getInputStream();
socketWriter = new PrintWriter(client.getOutputStream());
} catch (UnknownHostException e) {
System.out.println("Error setting up socket connection: unknown host at "
+ hostIP + ":" + hostPort);
} catch (IOException e) {
System.out.println("Error setting up socket connection: " + e);
}
}
public void tearDownConnection() {
try {
socketWriter.close();
socketReader.close();
} catch (IOException e) {
System.out.println("Error tearing down socket connection: " + e);
}
}
Class for handling connections to the server
public class ConnectionHandler implements Runnable {
private Socket socketToHandle;
public ConnectionHandler(Socket aSocketToHandle) {
socketToHandle = aSocketToHandle;
}
#Override
public void run() {
try {
PrintWriter streamWriter = new PrintWriter(
socketToHandle.getOutputStream());
BufferedReader streamReader = new BufferedReader(
new InputStreamReader(socketToHandle.getInputStream()));
String songToPlay = null;
while ((songToPlay = streamReader.readLine()) != null) {
if (songToPlay.equals("Playlist")) {
File songsTxt = new File(
"D:/Universitet i dr/JAVA/AudioPlayer/src/main/media/songsList.txt");
String song = null;
try {
FileReader reader = new FileReader(songsTxt);
BufferedReader songReader = new BufferedReader(reader);
while ((song = songReader.readLine()) != null) {
streamWriter.println(song);
}
} catch (FileNotFoundException e) {
System.out.println("File dosen't exist");
} catch (IOException e) {
System.out.println("Can't read from the file");
}
} else if (songToPlay.startsWith("Request ")) {
songToPlay = songToPlay.replaceFirst("Request ", "");
File songPath = new File(
"D:/Universitet i dr/JAVA/AudioPlayer/src/main/media/"
+ songToPlay);
BufferedInputStream inStream = new BufferedInputStream(
new FileInputStream(songPath));
BufferedOutputStream outStream = new BufferedOutputStream(
socketToHandle.getOutputStream());
byte[] buffer = new byte[4096];
for (int read = inStream.read(buffer); read >= 0; read = inStream.read(buffer)) {
outStream.write(buffer, 0, read);
}
}
}
} catch (Exception e) {
System.out.println("Error handling a client: " + e);
}
}

Categories