I am making an android music player. One of the features of the app is that it can connect to another device via sockets and then stream files over that connection. Right now, I have the app connecting to my computer with a ServerSocket. What I want is to load an mp3 on my laptop, get all the bytes from the file and send them over the socket. Then The android app should play the bytes as they are received. I was able to write all the bytes to an mp3 file on my phone, but I am wondering if there is a way to play the bytes as they come in without having to download it. I'm using a MediaPlayer for playback.
Here is my code on the android app for receiving data.
Socket socket = new Socket("ip", port);
out = new DataOutputStream(socket.getOutputStream());
out.write("0\r\n".getBytes());
out.flush();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
InputStream inS = socket.getInputStream();
String line;
FileOutputStream newFile = new FileOutputStream(path+"test.mp3");
byte[] by = new byte[BUFFER_SIZE];
int read;
do{
read = inS.read(by,0,BUFFER_SIZE);
newFile.write(by,0,read);
}while(read>0);
And here is my code on the laptop (which is the server side).
Path path = "path to mp3";
byte[] b = Files.readAllBytes(path);
int portNum = 5000;
ServerSocket ss = new ServerSocket(portNum);
while(true)
{
System.out.println("waiting for connection:");
Socket clientSocket = ss.accept();
System.out.println("Got client");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line = in.readLine();
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
System.out.println(line);
byte[] by = new byte[BUFFER_SIZE];
FileInputStream s = new FileInputStream(path.toString());
int rc = s.read(by);
while(rc>0)
{
System.out.println(rc);
out.write(by,0,rc);
rc = s.read(by,0,BUFFER_SIZE);
}
s.close();
Is there a way I can create a MediaPlayer and make it's data source the byte array being read in and have it play simultaneously?
Related
I am using the sample from Microsoft's Async Socket Listener. I got everything working fine, I am able to send files and data etc. However, I am struggling with trying to keep the socket open. I do not want to close the socket and re-open for every file I am sending. I want to keep it open until all files are sent. I assume the issue is in the 'SendCallback' but I can not seem to get it to work.
.Net Code
Private Shared Sub SendCallback(ar As IAsyncResult)
Try
' Retrieve the socket from the state object.
Dim handler As Socket = DirectCast(ar.AsyncState, Socket)
' Complete sending the data to the remote device.
Dim bytesSent As Integer = handler.EndSend(ar)
'trying to receive again - I added this after commenting out the below lines but am missing something.
Dim state As StateObject = DirectCast(ar.AsyncState, StateObject)
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
'The below lines are what was there, I tried to comment out and use the above lines trying to receive again but it does not work. I assume I am missing something simple but can not find anything useful. Any help would be appreciated.
'handler.Shutdown(SocketShutdown.Both)
'handler.Close()
Catch e As Exception
PubVars.ServerStatus = e.ToString
End Try
End Sub
I know I do not want to close the socket until all is sent but I am not sure what i am missing. I want to send the first file, then send back to the client a status update which all works well. Then when the client receives the status update, I want to send the next file and so on.
Android Code:
Socket socket = null;
try {
socket = new Socket("localhost", 11000);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
String FileName = "my.jpg";
String FilePath= Environment.getExternalStorageDirectory() + "/mydir/" + FileName;
File f= new File(FilePath);
byte[] data= readFileToByteArray(f);
String strbase64 = Base64.encodeToString(data, Base64.DEFAULT);
//I chose to pass the filename as part of my header string then parse it out on server
output.println("<HEADER>" + FileName + "</HEADER>" + strbase64 + "<EOF>");
output.flush();
InputStream in = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder returnString = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
returnString.append(line).append('\n');
}
Log.i("INPUT",returnString.toString());
//If true run the next one
//SEND NEW FILE
Log.i("NEXT","STARTING NEXT FILE");
FileName = "my2.png";
FilePath= Environment.getExternalStorageDirectory() + "/mydir/" + FileName;
f= new File(FilePath);
data= readFileToByteArray(f);
strbase64 = Base64.encodeToString(data, Base64.DEFAULT);
output.println("<HEADER>" + FileName + "</HEADER>" + strbase64 + "<EOF>");
output.flush();
in = socket.getInputStream();
r = new BufferedReader(new InputStreamReader(in));
returnString = new StringBuilder();
while ((line = r.readLine()) != null) {
returnString.append(line).append('\n');
}
Log.i("INPUT",returnString.toString());
//END ANOTHER FILE
output.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm new in socket. I really need your help.
I have create a socket client in android, and send the server a picture successfully. The next task what I want to do is receiving a JSON file from the server as the reply. However, after I close the outstream, it always tell me, " Socket is closed".
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//write out the stream
out.close();
InputStream inputStream = socket.getInputStream();
//!!it always throws SocketException, and tell me socket is closed
byte buffer[] = new byte[1024 * 4];
int temp = 0;
// read data from inputStream
while ((temp = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, temp));
}
I have tried many ways to solve it.
1.close the outstream lately
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//write out the stream
InputStream inputStream = socket.getInputStream();
byte buffer[] = new byte[1024 * 4];
int temp = 0;
//!!My client seems to wait for some messages from server.
//However, since I didn't close the outputStream, the server can't stop writing the file from my outputStream.
//As a result, the server can't send back JSON file to me as a reply.
//My server and client all go blocked.
while ((temp = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, temp));
}
out.close();
2.connect the socket again
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//write out the stream
out.close();
socket.connect(sc_add,2000);
//!!it will tell me the socket is already connected this time
InputStream inputStream = socket.getInputStream();
//it always throws SocketException, and tell me socket is closed
byte buffer[] = new byte[1024 * 4];
int temp = 0;
// read data from inputStream
while ((temp = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, temp));
}
Thank you for your help.
I'm trying to print a PDF from within my android application. But everytime i try to print my printed page contains weird data like:
java.io.FileInputStream#418479b0
I assume that my pdf isn't being rendered in the correct way...
Does anybody now how i can correctly convert my pdf to my outputstream?
I already tried the code from this question(Printing pdf in android), but then i get following output on my printed page:
Filter/FlateDecode/Length 69 >>stream
Can anybody help me? :)
This is my code:
Socket socket = new Socket();
String sIP = "192.168.0.250";
String sPort = "9100";
InetSocketAddress socketAddress = new InetSocketAddress(sIP, Integer.parseInt(sPort));
DataOutputStream outputStream;
try{
//file init
File pdfFile = new File(file);
byte[] byteArray=null;
InputStream inputStream = new FileInputStream(pdfFile);
String inputStreamToString = inputStream.toString();
byteArray = inputStreamToString.getBytes();
inputStream.close();
//Socket init
socket.connect(socketAddress, 3000);
outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.write(byteArray);
outputStream.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
You could try something like this to get the byteArray:
//file init
File pdfFile = new File(file);
byte[] byteArray = new byte[(int) pdfFile.length()];
FileInputStream fis = new FileInputStream(pdfFile);
fis.read(byteArray);
fis.close();
I have a simple SQLite database on my PC containing one table. I have the same SQLite database in my Android app. The data changes on the PC version of the database from time to time. How do I go about syncing the data from the SQLite database on the PC to the SQLite database on the Android device?
This is a simple solution with sockets:
Server side :
ServerSocket servsock = new ServerSocket(2004);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
BufferedReader input = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
String serverResponse = input.readLine();
// sendfile
File myFile = new File("C://XXXX/XXXX/XXXXX.db");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
Client side :
private String serverIpAddress = "xxx.xxx.xxx.xxx";
private static final int REDIRECTED_SERVERPORT = 2004;
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
int filesize = 6022386;
int bytesRead;
int current = 0;
byte[] mybytearray = new byte[filesize];
InputStream is = socket.getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(is));
FileOutputStream fos = new FileOutputStream(
"/data/data/XXXXX/databases/XXXXX.db");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current,
(mybytearray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
bos.close();
socket.close();
This will take quite some work to get it running without problems. Here is how I'd go:
Use a receiver on the Android to detect when USB is plugged. When this is detected, copy your database file over to the SD Card in a folder of your choice (say /data/com.example.package/sync/db.sqlite).
From your PC, detect mass storage devices. Scan the SD Card to check if you find the file at the path above. If not, there is nothing to sync. If yes, then you'll need to perform some DB comparison (google for algorithms and depending on your data you have different possibilities here)
Now you should be having a 3rd database file (the result of the sync between PC and Android databases). This file can be copied to the mass storage (your SD card) at the same place as it was taken.
Use a receiver on the Android to detect when the SDCard is mounted. When this is detected, simply copy the database file from /data/com.example.package/sync/db.sqlite to your application package directory.
We did that for a music application. This is not a trivial task but we managed to get it working quite nicely.
private void doFileDownload() throws Exception {
BufferedInputStream in = null;
BufferedOutputStream out = null;
String url = "http://www.jimsonmok.com/server/uploads/"; //input
String file = "/sdcard/Shek Kip Mei MTR Station Exit A.3gp"; //output
try{
url += URLEncoder.encode("Shek Kip Mei MTR Station Exit A.3gp");
URL download = new URL(url);
URLConnection downloadConnection = download.openConnection(); //set up connection
in = new BufferedInputStream(downloadConnection.getInputStream());
out = new BufferedOutputStream(new FileOutputStream(file));
int contentlength = downloadConnection.getContentLength(); //getting the length of the file
for(int counter=0;counter < contentlength;counter++) //storing the binary I/O file
out.write(in.read());
}catch(IOException e){
}
in.close();
out.close();
}
I am trying to download an audio from the server using an android phone.
The code above I am using does not work in android.
Does anyone know the reasons?
Thanks a lot!