i want to ask some question for android socket. I create a sample app to send data to wifly module. But when i receive data from module i get socket timeout exception. Without setSoTimeout app freeze to inputStream.read. Here is my code:
package com.socket.wiflysocket;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
protected static final String TAG = "WIflySocket";
EditText textOut;
TextView textIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo == null || networkInfo.isConnected() == false) {
try {
throw new Exception("Network is not connected");
} catch (Exception e) {
e.printStackTrace();
}
}
else {
new SocketThread(textOut.getText().toString()).execute();
textOut.setText("");
}
}};
}
and asynkTask:
package com.socket.wiflysocket;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.util.Log;
public class SocketThread extends AsyncTask<String, Void, String>{
private static final String TAG = "SocketAsyncTask";
private static final int BUFFER_SIZE = 8;
private String textViewIn;
private String output;
private Socket socket = null;
private PrintWriter outputStream;
private InputStreamReader inputStream;
public SocketThread(String paramTextViewIn)
{
this.textViewIn = paramTextViewIn;
}
#Override
protected String doInBackground(String ...views) {
Log.d(TAG, "Execute");
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("1.2.3.4", 2000);
socket.setSoTimeout(2000);
outputStream = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
inputStream = new InputStreamReader(socket.getInputStream());
if(socket.isConnected()) {
this.sendDataWithString(textViewIn);
output = this.receiveDataFromServer();
}
this.closeSocket();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return output;
}
/*
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
return textViewOut;
}
*/
private void closeSocket() {
if (socket != null) {
if (socket.isConnected()) {
try {
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void sendDataWithString(String message) {
if (message != null) {
outputStream.write(message);
outputStream.flush();
}
}
private String receiveDataFromServer() {
String message = "";
try {
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = inputStream.read(buffer)) != -1) {
message += new String(buffer).substring(0, charsRead);
}
closeSocket();
return message;
} catch (IOException e) {
//TODO work around
return message;
//return "Error receiving response: " + e.getMessage();
}
}
}
Permission that I add are :
android.permission.INTERNET;
android.permission.ACCESS_NETWORK_STATE
Can you suggest me, what is wrong, and how to fix this issue.
Thanks
Try this -
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
or this -
Reader r = new InputStreamReader(conn.getInputStream());
String line;
StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
sb.append(chars, 0, len);
}
or this one -
byte[] resultBuff = new byte[0];
byte[] buff = new byte[1024];
int k = -1;
while((k = sock.getInputStream().read(buff, 0, buff.length)) > -1) {
byte[] tbuff = new byte[resultBuff.length + k];
System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); bytes
System.arraycopy(buff, 0, tbuff, resultBuff.length, k);
resultBuff = tbuff;
}
SocketFactory creates socket for you
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.net.SocketFactory;
...
private Socket socket = null;
public Reader reader = null;
public Writer writer = null;
protected void init(String host, int port) throws ClientException {
try {
socket = SocketFactory.getDefault().createSocket(host, port);
} catch (UnknownHostException e) {
throw new ClientException(e);
} catch (IOException e) {
throw new ClientException(e);
}
initDataManagers();
}
protected void initDataManagers() throws ClientException {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new ClientException(e);
} catch (IOException e) {
throw new ClientException(e);
}
}
Related
I have a an application which communicates between two android devices through socket. It seems like they do connect, but when data from the client socket is read by ServerSocket (using InputStream), it doesnot return the desired result (it is supposed to return somrthing like "21.24891706//95.23659845//ff8iuj67898n47fu" ).Instead I'm getting " [B#416b9488" as the message.
My client runs an AsyncTask and server runs a Thread.
Can you please help me solve this problem? Any help will is appreciated. Thanks in advance.
Here is Server.java which runs on the server:
import android.content.Context;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
public class Server {
Context context;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
ShowConnectedStudents activity;
public Server(ShowConnectedStudents callingActivity) {
activity = callingActivity;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
byte buffer[] = new byte[1024];
int bytesRead;
String message;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket=new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(socketServerPORT));
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
message = "";
InputStream input = socket.getInputStream();
BufferedInputStream br= new BufferedInputStream(input);
while ((bytesRead = br.read(buffer)) != -1 ) {
message += " " + buffer.toString();
}
message += socket.isConnected();
message+=":"+socket.isClosed();
input.close();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.status.setText("Message is: " + message);
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Here is Client.java which runs on the client:
import android.os.AsyncTask;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String status = "";
double Lat,Long;
String deviceId;
Socket socket = null;
ConnectToDevice activity;
byte buffer[] = new byte[1024];
int bytesRead;
Client(String addr, int port,double latitude,double longitude,String deviceIdentification,ConnectToDevice callingActivity) {
dstAddress = addr;
dstPort = port;
Lat=latitude;
Long=longitude;
deviceId=deviceIdentification;
activity=callingActivity;
if(dstAddress.charAt(0)=='/'){
dstAddress=dstAddress.substring(1);
}
}
#Override
protected Void doInBackground(Void... arg0) {
while(socket==null){
try {
socket = new Socket(dstAddress, dstPort);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream outputStream = socket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream,true);
printStream.print(Lat + "//" + Long+"//"+deviceId);
printStream.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
status = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
status = "IOException: " + e.toString();
} finally {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
activity.statusText.setText(Lat+ "//" + Long+"//"+deviceId);
super.onPostExecute(result);
}
}
toString() on a byte[] is not what you want, you're getting basically the memory address of the byte array
instead convert to a string, something like this
while ((bytesRead = br.read(buffer)) != -1 ) {
message += " " + new String(buffer, 0, bytesRead);
}
I have figured out another way, before reading this accepted answer. I'm posting it in case if it benefit anyone.
My data is text-only. So I wrapped the socket's input stream inside a Scanner.
InputStream input = socket.getInputStream();
Scanner scanner= new Scanner(input);
while(scanner.hasNextLine()){
message+=scanner.nextLine();
}
I am trying to develop an app in which
1.client sends request to server for connection(IP address+PORT no.)+sends data using "PrintStream"+Tries to read the data from Server(Using Inputstream)
2.Client creates the socket.
3.Server reads the data send by Client
4.SERVER writes the data using "PrintStream" at same time point no 3.
Problem is at point 4 Data written by SERVER is not Read by "INPUTSTREAM" of client(Point 1)
I dont know these Simultaneous operation are possible or not.If possible then how.If not then what is the alternate way?
Server Code
package com.example.loneranger.ser;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends Activity {
TextView ip;
TextView msg;
String data = "";
ServerSocket httpServerSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
ip.setText(getIpAddress() + ":"
+ 8080 + "\n");
Server server = new Server();
server.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (httpServerSocket != null) {
try {
httpServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "IP: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
private class Server extends Thread {
#Override
public void run() {
Socket socket = null;
try {
httpServerSocket = new ServerSocket(8888);
while(true){
socket = httpServerSocket.accept();
HttpResponseThread httpResponseThread =
new HttpResponseThread(
socket);
httpResponseThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class HttpResponseThread extends Thread {
Socket socket;
HttpResponseThread(Socket socket){
this.socket = socket;
}
#Override
public void run() {
BufferedReader BReader;
PrintWriter printer;
String request;
try { InputStream inputStream = socket.getInputStream();
BReader = new BufferedReader(new InputStreamReader(inputStream));
request = BReader.readLine();
Thread.sleep(500);
printer = new PrintWriter(socket.getOutputStream(), true);
printer.print("hello laundu");
printer.flush();
String ip123=socket.getInetAddress().toString();
printer.close();
BReader.close();
socket.close();
data += "Request of " + request
+ " from "+ ip123 + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(data);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
}
}
Client Code
mport android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
MainActivity activity;
OutputStream outputStream;
BufferedReader BReader;
String request;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse=textResponse;
this.activity=activity;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
Server server = new Server(socket);
server.start();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.print("futfujb");
out.flush();
/*
* notice: inputStream.read() will block if no data return
*/
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} /*finally {
if (socket != null) {
try {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
private class Server extends Thread {
Socket socket;
Server(Socket socket)
{
this.socket=socket;
}
#Override
public void run() {
try { //Thread.sleep(500);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
if(inputStream.available()>0)
{
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
inputStream.close();
socket.close();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
As I commented above, there is nothing in this code that corresponds to either of these steps:
2.Server gets the request creates new SOCKET connection.
(a) There is no request, and (b) the server does not create a new connection. The client creates it. The server accepts it.
3.Server reads the data send by Client.
The client doesn't send any data.
There are two problems here (at least):
The server is blocking in readLine() waiting for a message that the client never sends. So it never gets to its own send, so nothing is received by the client. Have the client send a request, as per the comments.
The client is incorrectly using available(). Remove this test and let the client fall through into the read loop. It will exit that when the peer (the server) closes the connection.
I am working on an android project. Where I am using Socket programming.
But I am getting
java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused.
from emulator.
I have changed the localhost to
"10.0.2.2" ("http://10.0.2.2/abc.php").
I have also followed the java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused.
But I did not get any solution.
Also please note emulator ip address doesn't match with localhost ip address.So I don't know how to get around this.
Here is the code requested for:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import android.util.Log;
import com.mekya.interfaces.IAppManager;
import com.mekya.interfaces.ISocketOperator;
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://billbahadur.com/demo/androidchat/android_im/";
private int listeningPort = 5550;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false)
{
appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public boolean sendMessage(String message, String ip, int port)
{
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
} catch (UnknownHostException e) {
return false;
//e.printStackTrace();
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
}
change android_im to android-im because that is what your folder name would be kept in the web server directory of your server. Also mention the port number of the server in the authentication address.
I want to send an audio file .mp3 file from android client to servlet server and save it in a location. If I play that saved .mp3 file in that location it should play.
My question is there a way to send a .mp3 file directly from client to server and retrieve that mp3 file in servlet.
My client side code is as follows:
package com.android.audiorecord;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.android.audiofileplayer.StreamingMp3Player;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
public class AudioRecordActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private String url = "QRFileSaveServlet";
String result;
byte[] value;
String s;
byte[] filebyte,clientbyte;
String readString;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private SubmitButton mSubmitButton = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
String fileresult = "";
HttpResponse response;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
/* public boolean saveas(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/media/audio/ringtones/";
String filename="examplefile"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
} */
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
// mRecorder.reset();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
class SubmitButton extends Button {
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
File f = new File(Environment.getExternalStorageDirectory()+"/audiorecordtest.mp3");
//
//byte[] file = fileresult.getBytes();
try {
filebyte = FileUtils.readFileToByteArray(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("$$$$$$$$$$$" + filebyte);
clientbyte = Base64.encode(filebyte, MODE_APPEND);//(filebyte, MODE_APPEND);
s= new String(clientbyte);
System.out.println("**************" + s);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Audiofile", s));
result = AudioServer.executePost(url, nameValuePairs);
result = result.trim();
System.out.println("response recieved " + result);
if(result!=null){
Bundle bundle = new Bundle();
Intent explicitIntent = new Intent(AudioRecordActivity.this,
StreamingMp3Player.class);
bundle.putString("result", result);
explicitIntent.putExtras(bundle);
startActivity(explicitIntent);
}
}
};
public SubmitButton(Context ctx) {
super(ctx);
setText("Save");
setOnClickListener(clicker);
}
}
public AudioRecordActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.mp3";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mSubmitButton = new SubmitButton(this);
ll.addView(mSubmitButton, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
in this can i send audiorecordtest.mp3 file direcly to server without encoding to byte[] and send it in namevalue pair.
My server side code is as follows:
package com.gsr.qrbarcode;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import com.android.gsr.utils.AudioSampleReader;
import com.android.gsr.utils.AudioSampleWriter;
import com.android.gsr.utils.Base64;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFileFormat.Type;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.apache.commons.io.FileUtils;
/**
* Servlet implementation class QRFileSaveServlet
*/
//#WebServlet("/QRFileSaveServlet")
public class QRFileSaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
AudioInputStream ais;
/**
* Default constructor.
*/
public QRFileSaveServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String qrfile= request.getParameter("Audiofile");
System.out.println("String Parameter \"" +qrfile );
byte[] audiofile=Base64.decode(qrfile);
String newStr = new String(audiofile);
// Display the contents of the byte array.
System.out.println("The new String equals \"" +newStr + "\"");
String filePath = this.getServletContext().getRealPath("/")+"";
System.out.println("Path of the file " + filePath);
String fileupload="AudioFileStorage";
//PrintWriter out = response.getWriter();
File f;
f= new File(filePath);
//int status = 0;
if(f.exists()) {
filePath += fileupload;
f = new File(filePath);
if(!f.exists()){
f.mkdir();
}
f = new File(filePath,"test.mp3");
if(!f.exists()) {
FileOutputStream fos = new FileOutputStream(f);
fos.write(audiofile);
fos.flush();
fos.close();
} else {
//out.println("failure");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try{
stream = response.getOutputStream();
// File mp3 = new File(mp3Dir + "/" + fileName);
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition","attachment; filename="+f );
response.setContentLength( (int) f.length() );
FileInputStream input = new FileInputStream(f);
buf = new BufferedInputStream(input);
int readBytes = 0;
while((readBytes = buf.read()) != -1)
stream.write(readBytes);
System.out.println("Response Stream"+stream);
} catch (IOException ioe){
throw new ServletException(ioe.getMessage());
} finally {
if(stream != null)
stream.close();
if(buf != null)
buf.close();
}
}
}
if (filePath == null || filePath.equals(""))
throw new ServletException(
"Invalid or non-existent mp3Dir context-param.");
URL url = null;
try{
url = f.toURL();
System.out.println("URL : "+ url);
System.out.println("Converting process Successfully");
}
catch (MalformedURLException me){
System.out.println("Converting process error");
}
//String rfilepath=this.getServletContext().getRealPath("/")+" AudioFileStorage/test.mp3";
//System.out.println("Path of the rfilepath " + rfilepath);
}
}
here can i get that audiorecordtest.mp3 file directly from client without decoding in server side and play it in this servlet
my server connection in local for client
executepost() is as follows:
package com.android.audio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class AudioServer {
static InputStream is;
private static String API_URL = "http://192.168.15.71:8088/QRBarCodeServer/";
public static String executePost(String apiurl,
ArrayList<NameValuePair> urlParameters) {
try {
// Create connection
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(API_URL + apiurl);
httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
// Get Response
// InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response1 = new StringBuffer();
while ((line = rd.readLine()) != null) {
response1.append(line);
response1.append('\r');
}
rd.close();
return response1.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String executeHttpGet(String apiurl) throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(API_URL + apiurl);
request.setURI(new URI(apiurl));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
here is simple way to do that
1: from android side read that .mp3 file and create base64String from it.
2: At servier side read this base64String and convert it back to .mp3 file.
to convert any file to base64String following is the process
File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
You can reach it using apache MultipartEntity:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(BASE_URL);
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("Audiofile", new FileBody(file, "audio/mpeg"));
post.setEntity(mpEntity);
HttpResponse res = client.execute(post);
Yea you can send this in Servlet there is Mime type mime means multimedia extension
I am sending code i can guarantee that it will work in Servlet in java and you should take
care for android by own
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendMp3Envious extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileName = (String) request.getParameter("file");
if (fileName == null || fileName.equals(""))
throw new ServletException(
"Invalid or non-existent file parameter in SendMp3 servlet.");
if (fileName.indexOf(".mp3") == -1)
fileName = fileName + ".mp3";
String mp3Dir = getServletContext().getInitParameter("mp3-dir");
if (mp3Dir == null || mp3Dir.equals(""))
throw new ServletException(
"Invalid or non-existent mp3Dir context-param.");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
stream = response.getOutputStream();
File mp3 = new File(mp3Dir + "/" + fileName);
//set response headers
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition", "attachment; filename="
+ fileName);
response.setContentLength((int) mp3.length());
FileInputStream input = new FileInputStream(mp3);
buf = new BufferedInputStream(input);
int readBytes = 0;
//read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
if (stream != null)
stream.close();
if (buf != null)
buf.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
hi i am trying to send a file through sockets in an android messenger. for some reason its not working. at times it does output a file but transfers no bytes that is the output file is of 0 bytes and sometimes the output or the received file is of 57 bytes precisely. following the code where i actually send the file :
public boolean sendFile(String ip, int port) {
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File("/sdcard/chats/gas.jpg/");
filesize = (int) f.length();
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream(f);
Log.i("SocketOP", "sendFILE-2");
byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.flush();
out.close();
fileIn.close();
Log.i("SocketOP", "sendFILE-3");
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
this is where i send the inputstream to the receivefile method :
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket) {
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
//PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
InputStream is=clientSocket.getInputStream();
if (inputLine.contains("Text") == true) {
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");
} else if (inputLine.contains("Text") == false) {
Log.i("SocketOP","filee");
appManager.fileReceived(is);
} else {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
}
}
}
and finally this is how i receive the file :
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
//int filesize=6022386; // filesize temporary hardcoded
int bytesRead;
final byte[] aByte = new byte[is.toString().length()];
if (is!= null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/gas1.jpg/");
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
}}
the following is the complete socketoperator file :
package hardy.scl.communication;
import hardy.scl.interfaces.IAppManager;
import hardy.scl.interfaces.ISocketOperator;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import android.util.Log;
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://10.10.10.100/chippers/";
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
public int filesize ;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
Socket fileSocket=null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
this.fileSocket=socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
InputStream is=fileSocket.getInputStream();
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("Text") == true)
{
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");}
else if
(inputLine.contains("Text") == false)
{
Log.i("SocketOP","filee");
appManager.fileReceived(is);
}
else{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
fileSocket.shutdownInput();
fileSocket.shutdownOutput();
fileSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
SocketOperator.this.sockets.remove(fileSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public boolean sendMessage(String message, String ip, int port)
{
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
//OutputStreamWriter outputStream = new OutputStreamWriter(socket.getOutputStream());
//outputStream.write("Text");
// outputStream.flush();
String flag = "Text";
message = message+flag;
out.println(message);
} catch (UnknownHostException e) {
return false;
//e.printStackTrace();
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
#Override
public boolean sendFile(String ip, int port) {
// TODO Auto-generated method stub
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File("/sdcard/chats/gas.jpg/");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
int readData;
byte[] buffer = new byte[1024];
bis.read(buffer, 0,buffer.length);
OutputStream os = socket.getOutputStream();
while((readData=bis.read(buffer))!=-1){
os.write(buffer,0,readData);
Log.i("SocketOP", "sendFILE-3");
}
} catch (IOException e) {
return false;
//e.printStackTrace();
}
// Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
return true;
}
}
This is my IMService service that runs and calls startlistening. i am totally cluless. its giving me an error as suspected. how do i go about resolving this now..
IMService code block :
public void onCreate()
{
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
// showNotification();
conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
// Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
timer = new Timer();
Thread thread = new Thread()
{
#Override
public void run() {
//socketOperator.startListening(LISTENING_PORT_NO);
Random random = new Random();
int tryCount = 0;
while (socketOperator.startListening(10000 + random.nextInt(20000)) == 0 )
{
tryCount++;
if (tryCount > 10)
{
// if it can't listen a port after trying 10 times, give up...
break;
}
}
}
};
thread.start();
}
Try this for fileReceived
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/gas1.jpg/");
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(aByte)) != -1) {
bos.write(aByte, 0, bytesRead);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
}}
EDIT
You can use 2 sockets, listening on different ports. E.g.
MESSAGE_PORT = 20000
FILE_PORT = 20001
And you run 2 ReceiveConnections, e.g. ReceiveFileConnection and ReceiveMessageConnection. I don't know where do you start port listening, it's not in your code above.
In client you'll also need to split sending to 2 part, message sender sends to MESSAGE_PORT and file sends files to FILE_PORT.
EDIT2
http://pastebin.com/MfMuSF2Q
I split ReceiveConnection into 2 classes ReceiveMessageConnection and ReceiveFileConnection.
I modified method startListening, so it takes parameter which listener we want to start message or file. So you need to call it twice like
startListening(MESSAGE_PORT, true);
startListening(FILE_PORT, false);
But call them in different threads.
To send message you call sendMessage("Message", ip, MESSAGE_PORT) and for files sendFile(ip, FILE_PORT).
Hope this will help.