Stream audio record from android device toanother - android

I want to make stream voice between microphone of android device to speaker of another, so I used Audiorecord !!
The activity that sends voice is :
public class MainActivity extends Activity {
AudioRecord recorder;
private int sampleRate = 44100;
int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
private boolean status = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton.setOnClickListener (startListener);
stopButton.setOnClickListener (stopListener);
minBufSize += 4096;
System.out.println("minBufSize: " + minBufSize);
}
private final OnClickListener stopListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
status = false;
recorder.release();
}
};
private final OnClickListener startListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
status = true;
try {
DatagramSocket socket = new DatagramSocket();
Log.d("VS", "Socket Created");
byte[] buffer = new byte[minBufSize];
Log.d("VS","Buffer created of size " + minBufSize);
DatagramPacket packet;
final InetAddress destination = InetAddress.getByName("addresse");
Log.d("VS", "Address retrieved");
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,sampleRate,channelConfig,audioFormat,minBufSize*10);
Log.d("VS", "Recorder initialized");
recorder.startRecording();
while(status == true) {
//reading data from MIC into buffer
minBufSize = recorder.read(buffer, 0, buffer.length);
//putting buffer in the packet
packet = new DatagramPacket (buffer,buffer.length,destination,port);
socket.send(packet);
System.out.println("MinBufferSize: " +minBufSize);
}
} catch(UnknownHostException e) {
Log.e("VS", "UnknownHostException");
} catch (IOException e) {
e.printStackTrace();
Log.e("VS", "IOException");
}
}
};
}
and the activity in the android revice is :
public class MainActivity extends Activity {
public static DatagramSocket socket;
private AudioTrack speaker;
private boolean status = true;
#SuppressLint("CutPasteId")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.receive_button);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
status = true;
try {
DatagramSocket socket = new DatagramSocket(port);
byte[] buffer = new byte[4096];
//minimum buffer size. need to be careful. might cause problems. try setting manually if any problems faced
int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
speaker = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRate,channelConfig,audioFormat,minBufSize,AudioTrack.MODE_STREAM);
speaker.play();
while(status == true) {
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
Log.d("VR", "Packet Received");
buffer=packet.getData();
Log.d("VR", "Packet data read into buffer");
speaker.write(buffer, 0, minBufSize);
Log.d("VR", "Writing buffer content to speaker");
}
} catch(UnknownHostException e) {
Log.e("VS", "UnknownHostException");
} catch (IOException e) {
e.printStackTrace();
Log.e("VS", "IOException");
}
}
});
Button button2 = (Button) findViewById(R.id.receive_button);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
status = false;
speaker.release();
}
});
}
}
the sender works but when I click the button in the receiver app, that makes error : NULL POINTER EXCEPTION!!
How can I resolve this?
Thanks!

Related

How to Set Sample Rate on Text to Speech - Android

In the output of my text to Speech, I need to set Sampling rate about to 32000 Hz with Pitch - 1 and SpeechRate - 0.2 (which I already did). But I can't set Sample Rate.
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
tts.setLanguage(Locale.US);
tts.setSpeechRate((float) 0.2);
tts.setPitch((float) 1);
}
}
}, TextToSpeech.Engine.KEY_FEATURE_NETWORK_SYNTHESIS);
I used AudioTrack to set Sample Rate but it took lots of time because I have to first TTS synthesizeToFile then I play it in AudioTrack.
HashMap<String, String> myHasRead = new HashMap<String, String>();
myHasRead.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, outPutS);
String StorePath = Environment.getExternalStorageDirectory().getAbsolutePath();
File myF = new File(StorePath+"/tempAudio.wav");
try {
myF.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
tts.setOnUtteranceProgressListener(new TtsUtteranceListener());
tts.synthesizeToFile("Bla Bla bla",myHasRead, StorePath+"/tempAudio.wav");
....
private class TtsUtteranceListener extends UtteranceProgressListener {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
playWav();
}
#Override
public void onError(String utteranceId) {
}
}
public void playWav(){
int minBufferSize = AudioTrack.getMinBufferSize(32000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
int bufferSize = 512;
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 32000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath();
int i = 0;
byte[] s = new byte[bufferSize];
try {
FileInputStream fin = new FileInputStream(filepath + "/tempAudio.wav");
DataInputStream dis = new DataInputStream(fin);
at.play();
while((i = dis.read(s, 0, bufferSize)) > -1){
at.write(s, 0, i);
}
at.stop();
at.release();
dis.close();
fin.close();
} catch (FileNotFoundException e) {
// TODO
e.printStackTrace();
} catch (IOException e) {
// TODO
e.printStackTrace();
}
}
There is any way to set sample rate Direct to TTS like tts.setSampleRate(32000); or get Stream from TTS to AudioTrack like DataInputStream dis = new DataInputStream(tts.speak("bla bla bla").getDataInputStream); . In Short I need Chipmunk's Text to Speech for Android but without synthesizeToFile or direct stream TTS voice Data in AudioTrack without saving output of TTS.
You can't set TTS sampling Rate directly:
I did something like this in a project ( Dint use TTS )
This might help you,
To play record with different voice type :-
waveSampling=90000; (Chipmunk)
waveSampling=24200; ("SLOW MOTION")
waveSampling=30000;("BANE") /batman character
waveSampling=18000;(Ghost)
waveSampling=70000;(Bee)
waveSampling=60000;(Woman)
waveSampling=37000; (Normal)
void playRecord() throws IOException {
int minBufferSize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
int bufferSize = 512;
at = new AudioTrack(AudioManager.STREAM_MUSIC, waveSampling, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath();
int i = 0;
byte[] s = new byte[bufferSize];
try {
FileInputStream fin = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Voice Changer/temp/"+filename+".wav");
DataInputStream dis = new DataInputStream(fin);
at.play();
while((i = dis.read(s, 0, bufferSize)) > -1){
at.write(s, 0, i);
}
at.stop();
at.release();
dis.close();
fin.close();
openmenu();
} catch (FileNotFoundException e) {
// TODO
e.printStackTrace();
} catch (IOException e) {
// TODO
e.printStackTrace();
}
}
To save the Audio :-
public void save() throws IOException {
Random r = new Random();
final int i1 = r.nextInt(80 - 65) + 65;
File tempfile2=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Voice Changer/temp/"+i1+filename+".wav");
savedfile=Environment.getExternalStorageDirectory().getAbsolutePath()+"/Voice Changer/"+"VOICE CHANGER"+i1+filename+".mp3";
Toast.makeText(this, "File Saved", Toast.LENGTH_SHORT).show();
rawToWave(tempfile,tempfile2);
File wavFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Voice Changer/temp/"+i1+filename+".wav");
IConvertCallback callback = new IConvertCallback() {
#Override
public void onSuccess(File convertedFile) {
File newfile=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Voice Changer/"+"VOICE CHANGER"+i1+filename+".mp3");
File savedmp3=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Voice Changer/temp/"+i1+filename+".mp3");
Toast.makeText(MainActivity.this, "SUCCESS: " + newfile.getPath(), Toast.LENGTH_LONG).show();
try {
copyit(savedmp3,newfile);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Exception error) {
Toast.makeText(MainActivity.this, "ERROR: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
};
Toast.makeText(this, "Converting audio file...", Toast.LENGTH_SHORT).show();
AndroidAudioConverter.with(this)
.setFile(wavFile)
.setFormat(cafe.adriel.androidaudioconverter.model.AudioFormat.MP3)
.setCallback(callback)
.convert();
}
The output will be a .mp3 file. If you want the output fast you can use .wav format.

how can i transfer voice between client and server?

I'm developing voice chat App.streaming voice between client and server.
i had tried with Datagramsocket but has a lota problems.
I'M trying with Tcp this time. but i couldn't transfer data.what's wrong with my code?
client :
public void startStreaming() {
Thread streamThread = new Thread(new Runnable() {
#Override
public void run() {
try {
int minBufSize =AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
Log.d("VS", "Socket Created.c");
byte[] buffer = new byte[256];
Log.d("VS","Buffer created of size .c" + minBufSize);
DatagramPacket packet;
final InetAddress destination = InetAddress.getByName(target.getText().toString());
port=Integer.parseInt(target_port.getText().toString());
Socket socket=new Socket(destination,port);
Log.d("VS", "Address retrieved.c");
Log.d("VS", "");
if (minBufSize != AudioRecord.ERROR_BAD_VALUE) {
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,sampleRate,channelConfig,audioFormat,minBufSize*=10);
Log.d("VS", "Recorder initialized.c");
if (recorder.getState() == AudioRecord.STATE_INITIALIZED)
recorder.startRecording();}
while(status == true) {
//reading data from MIC into buffer
minBufSize = recorder.read(buffer, 0, buffer.length);
Log.d("", ""+buffer.length);
//encoding to base64
// String buffer1= Base64.encodeToString(buffer, Base64.DEFAULT);
//putting buffer in the packet
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(buffer);
// packet = new DatagramPacket (buffer,buffer.length,destination,port);
// socket.send(packet);
}
} catch(UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("IOException message:",e.getMessage().toString());
}
}
});
streamThread.start();
}
server :
public void startReceiving() {
Thread receiveThread = new Thread (new Runnable() {
#Override
public void run() {
try {
int minBufSize =4096;//recorder.getMinBufferSize(sampleRate,channelConfig,audioFormat);
ServerSocket serversocket = new ServerSocket(50005);
// DatagramSocket socket = new DatagramSocket(50005);
byte[] buffer = new byte[2560];
if (minBufSize != AudioRecord.ERROR_BAD_VALUE) {
speaker = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRate,channelConfig,audioFormat,minBufSize,AudioTrack.MODE_STREAM);
speaker.play();
Log.d("VR", "spekaer playing...");
}
// }
//minimum buffer size. need to be careful. might cause problems. try setting manually if any problems faced
// int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
Log.d("VR", ""+status);
InputStream is;
ObjectInputStream ois;
while(status == true) {
//DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket = serversocket.accept();
is = socket.getInputStream();
ois = new ObjectInputStream(is);
// socket.receive(packet);
Log.d("VR", "Packet Received.s");
//reading content from packet
// buffer=packet.getData();
Log.d("VR", "Packet data read into buffer.s");
//sending data to the Audiotrack obj i.e. speaker
speaker.write( ois.toString().getBytes(), 0, minBufSize);
Log.d("VR", "Writing buffer content to speaker.s");
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i think the problem is transfering the voice.
please give me your best help
client side :
BufferedWriter input;
while(status == true) {
int bufferReadResult = recorder.read(buffer, 0, buffer.length);
dos.write(buffer,0,bufferReadResult);
dos.flush();
}

Android socket does not receive all the bytes of an image [duplicate]

This question already has answers here:
Android: Image received over socket is corrupted
(2 answers)
Closed 8 years ago.
Hi I'm having problem receiving an image
In the last while it simply doesn't receive all the bytes and the program does not exit the while condition. With a 77970 bytes image, this receives 61592 bytes then just does nothing. It keeps stuck in the while. I dunno what to do, thanks for any help.
public class FileActivity extends Activity {
private EditText serverIp, getPort, exT;
private Button connectPhones;
private TextView tv, tvIP;
private Boolean connected = false;
private String serverIpAddress, portStr,ex;
private Socket socket;
private int port, len;
private String filepath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
exT = (EditText) findViewById(R.id.editText1);
tvIP = (TextView) findViewById(R.id.IPtv);
tv = (TextView) findViewById(R.id.Portatv);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
getPort = (EditText) findViewById(R.id.server_port);
}
public void connectListener(View v)
{
tv.setVisibility(View.GONE);
connectPhones.setVisibility(View.GONE);
getPort.setVisibility(View.GONE);
serverIp.setVisibility(View.GONE);
tvIP.setTextSize(16f);
tvIP.setText("Connesso");
exT.setVisibility(View.GONE);
ex = exT.getText().toString();
if (!connected) {
serverIpAddress = serverIp.getText().toString();
portStr = getPort.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
public class ClientThread implements Runnable
{
#Override
public void run() {
// TODO Auto-generated method stub
port = Integer.parseInt(portStr);
socket = new Socket();
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connessione in corso...");
socket = new Socket(serverAddr, port);
Log.d("ClientActivity", "C: Connesso!");
connected = true;
DataInputStream dis;
try {
dis = new DataInputStream(socket.getInputStream());
int bytes;
byte[] b = new byte[32];
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String l = in.readLine();
//String line = Integer.toString(l);
Log.d("PROVA", l);
try
{
len = Integer.parseInt(l); Log.d("CLIENT", Integer.toString(len));
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
byte[] img = new byte[1024]; //1082922
FileOutputStream fos = new FileOutputStream("/sdcard/" + ex);
BufferedOutputStream bos = new BufferedOutputStream(fos);
/*bytes = dis.read(img, 0, img.length);
bos.write(img, 0, img.length);*/
int count = 0;
while ((bytes = dis.read(img)) != -1) {
count += bytes;
Log.d("CLIENT", Integer.toString(count));
Log.d("TEST", Integer.toString(bytes));
//Write to file
bos.write(img, 0, bytes);
}
//bos.flush();
//bos.close();
Log.d("TCP", "Save to file");
} catch(IOException e){
e.printStackTrace();
}
} catch (Exception e) {
Log.e("ClientActivity", "C: Errore", e);
connected = false;
}
}
}
#Override
protected void onStop() {
super.onStop();
if(connected == true)
{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Server:
public class FileActivity extends Activity {
private String test;
private FileInputStream fileInputStream;
private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;
private byte [] mybytearray;
private String tmp = null;
private TextView tv;
private File myFile;
private int l;
private String path;
private EditText editText;
private ServerSocket serverSocket;
private Socket client;
public static String SERVERIP = "10.0.2.15";
private final int SERVERPORT = 8080;
private byte [] imgbyte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
tv = (TextView) findViewById(R.id.textView1);
editText = (EditText) findViewById(R.id.editText1);
SERVERIP = getLocalIpAddress();
Thread sThread = new Thread(new ServerThread());
sThread.start();
}
public void sendListener(View v) {
tmp = editText.getText().toString();
path = "/sdcard/" + tmp;
myFile = new File(path);Log.d("SERVER", "WORKS");
if(myFile.exists())
{
l = (int) myFile.length();Log.d("SERVER", "WORKS");
tv.setText(path + " Size:" + Integer.toString(l));
tmp = Integer.toString(l); Log.d("SERVER", "WORKS");
test = tmp;
Thread t = new Thread(new sSend());
t.start();
}
else
{
tv.setText("Il file non esiste");
}
}
public class sSend implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
out.println(test);
//out.close();
Log.d("SERVER", "WORKS");
byte[] mybytearray = new byte[1024]; //create a byte array to file
Log.d("SERVER", "WORKS");
fileInputStream = new FileInputStream(myFile);
bufferedInputStream = new BufferedInputStream(fileInputStream);
Log.d("SERVER", "WORKS");
//bufferedInputStream.read(mybytearray, 0, mybytearray.length); //read the file
Log.d("SERVER", "WORKS");
try{
outputStream = client.getOutputStream();
} catch(Exception e)
{
Log.d("OUTPUT", "UFFFF");
e.printStackTrace();
}
Log.d("SERVER", "WORKS");
int count = 0;
int size = 0;
while((count = bufferedInputStream.read(mybytearray, 0 , mybytearray.length)) != -1)
{
// count = bufferedInputStream.read(mybytearray, 0 , mybytearray.length);
size += count;
Log.d("SERVER", "SEND");
try{
outputStream.write(mybytearray, 0, count);
} catch(Exception e) {
e.printStackTrace();
}
Log.d("TEST", Integer.toString(count));
}
Log.d("SERVER", "DONE");
Log.d("SERVER", Integer.toString(size));
}catch(Exception e){
e.printStackTrace();
}
}
}
public class ServerThread implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(SERVERPORT);
client = serverSocket.accept();
//outputStream = client.getOutputStream();
Log.d("SERVER", "Connesso");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("TEST", "UFFFAAA");
}
}
}
private String getLocalIpAddress() {
String tmp = "";
int i = 0;
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress())
{
tmp += "IP: " + inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return tmp;
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This looks like a repost. Why did you start a new thread? The other one was not ready yet. We had discovered some problems and you do not even mention them here. OP tries to send file size first and then the content. Also the client should read the file size first but it is a complete mess.

How to receive Digital Input from arduino using UDP in Android?

Actually I want to write a program in which whenever a button is pressed on specific digital pin of Arduino, Android receives that signal using UDP and performs tasks accordingly.
This is the Arduino code snippet:
void loop() {
buttonState = digitalRead(12);
if (buttonState == HIGH) {
// ToDo when push button is pressed
}
else {
Udp.beginPacket(Udp.remoteIP(),Udp.remotePort());
Udp.write("anything here");
Udp.endPacket();
}
This is my Android code:
public class Server implements Runnable
{
String serverHostname1, serverHostname2;
DatagramSocket d1;
InetAddress ip, retiip;
DatagramPacket send, rec;
String modifiedSentence;
public static String TAG = "SERVER";
DatagramSocket serverSocket;
public void run() {
Log.d(TAG, "Service Started");
try {
serverSocket = new DatagramSocket(8032);
} catch (SocketException e) {
e.printStackTrace();
}
Log.d(TAG, "Service Started");
byte[] receiveData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
Log.d(TAG, "Service Started");
try {
serverSocket.receive(receivePacket);
} catch (IOException e) {
e.printStackTrace();
}
String sentence = new String(receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
Log.d(TAG, "Service Started");
Log.d(TAG, "Received " + sentence);
}
}

android socket file transfer

Need help... I have understood how to make server-client socket conection... It works fie... Now I want to transfer files from server to client and back.... here are my sources...
Socket server...
public class ServerActivity extends Activity {
private TextView serverStatus;
// default ip
public static String SERVERIP = "192.168.1.1";
// designate a port
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
/////////////////////////////////
File myFile = new File ("/sdcard/frostwire.apk");
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 = client.getOutputStream();
System.out.println("Sending...");
serverStatus.setText("sending 123.exe...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
client.close();
////////////////////////////
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
#Override
public void run() {
// do whatever you want to the front end
// this is where you can be creative
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
// gets the ip address of your phone's network
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Socket Client...
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
int filesize; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
////////// // receive file
byte [] mybytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("/sdcard/frostwire.apk");
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();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
socket.close();
//////////////////////////////
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
Pieces of source which are marked by "///////" don't work.... Help
Better you replace the following your code
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
with the following one
do {
bytesRead =is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead > 0)
{
current += bytesRead;
}
} while(bytesRead > 0);
Then try it
after going through above discussion i would like to add few comments-
Have you added permission code for reading sdcard in android manifest file ? If not you should add following code as the server is accessing External Storage. Do for the client also to write in external storage.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Else, the directory you have provided is not correct. Check the directory.
In the client program, you have defined file_size which is not assigned any value nowhere in the program.
I would also like to suggest that, the file_size in the client program should be greater than the file to be transfer and size is in byte.

Categories

Resources