UDP with sequence numbers - java

I am trying to implement a Reliable UDP protocol for a class assignment in Java. I have managed to add the acknowledgments to every datagram packet that is received, but I am having trouble implementing Sequence Numbers in the datagram packets that I am sending.
Can anyone suggest an easy method to implement this?
#EJP I have tried implementing what you just suggested. This is my code till now (its still very raw - i was using hit and try method to implement it)
Server side
public class TestServer extends Activity {
private DatagramSocket serverSocket;
Thread serverThread = null;
byte[] incomingData;
byte[] outgoingData;
//int numBytesRead = 0;
int ackSent = 0;
int numPackRecv = 0;
int BUF_SIZE = 1024;
String msg = "ACK";
BufferedInputStream data=null;
BufferedOutputStream out =null;
public static final int SERVERPORT = 6000;
String outputFile = "/sdcard/Movies/asddcopy.mp4";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_server);
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (Exception e) {
Log.d("SERVER", "Inside onStop()");
Log.d("SERVER", Log.getStackTraceString(e));
}
}
class ServerThread implements Runnable {
#SuppressLint("NewApi")
public void run() {
try {
serverSocket = new DatagramSocket(SERVERPORT);
incomingData = new byte[BUF_SIZE];
//outgoingData = new byte[512];
outgoingData = msg.getBytes();
long startRxPackets = TrafficStats.getUidRxPackets(Process.myUid());
long startTime = System.nanoTime();
out = new BufferedOutputStream(new FileOutputStream(outputFile, true));
while (!Thread.currentThread().isInterrupted()) {
//serverSocket.setSoTimeout(5000);
while (true) {
try{
//DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length);
DatagramPacket incomingPacket = new DatagramPacket(incomingData, BUF_SIZE);
serverSocket.receive(incomingPacket);
byte[] data = incomingPacket.getData();
//out.write(data,0,incomingPacket.getLength());
//String msg = new String(incomingPacket.getData());
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
if (is == null) {
is = new ObjectInputStream(in);
}
Message msg = (Message) is.readObject();
System.out.println(msg.getSeqNo());
/*if ("END".equals(msg.substring(0, 3).trim())) {
Log.d("SERVER", "Inside END condition");
break;
}*/
out.write(msg.getData(),0,msg.getData().length);
numPackRecv += 1;
Log.d("SERVER", "Packet Received: " + numPackRecv);
InetAddress client = incomingPacket.getAddress();
int client_port = incomingPacket.getPort();
DatagramPacket outgoingPacket = new DatagramPacket(outgoingData, outgoingData.length, client, client_port);
serverSocket.send(outgoingPacket);
ackSent += 1;
//Log.d("SERVER","Packet Received: " + numPackRecv + " :: " + "Ack Sent: " + ackSent);
}catch(Exception e) {
Log.d("SERVER", "Inside run() ex1");
Log.d("SERVER", Log.getStackTraceString(e));
break;
}
}
out.close();
serverSocket.disconnect();
serverSocket.close();
Log.d("SERVER", "Transfer Complete");
Log.d("SERVER", "Actual Time elapsed = " + (System.nanoTime() - startTime)/Math.pow(10, 9) + " s");
Log.d("SERVER", "Total Packets Received = " + Long.toString(TrafficStats.getUidRxPackets(Process.myUid()) - startRxPackets));
Log.d("SERVER", "Packets Received from Socket = " + numPackRecv);
break;
}
out.close();
serverSocket.disconnect();
serverSocket.close();
/* Log.d("SERVER", "Transfer Complete");
Log.d("SERVER", "Actual Time elapsed = " + (System.nanoTime() - startTime)/Math.pow(10, 9) + " s");
Log.d("SERVER", "Total Packets Received = " + Long.toString(TrafficStats.getUidRxPackets(Process.myUid()) - startRxPackets));
Log.d("SERVER", "Packets Received from Socket = " + numPackRecv);*/
}catch (Exception e) {
Log.d("SERVER", "Inside run() ex2");
Log.d("SERVER", Log.getStackTraceString(e));
serverSocket.disconnect();
serverSocket.close();
}
}
}
This is the Client side
public class TestClient extends Activity { private DatagramSocket clientSocket;
byte[] incomingData;
int BUF_SIZE = 500;
int numBytesRead = 0;
int numPackSent = 0;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "10.0.0.22";
String inFile = "/sdcard/Movies/asdd.mp4";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_client);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
new workInProgress().execute("");
}
private class workInProgress extends AsyncTask<Object, Object, Object> {
#SuppressLint("NewApi")
#Override
protected Object doInBackground(Object... params) {
try {
Log.d("CLIENT", "Sending a file to the server...");
BufferedInputStream inputBuf = new BufferedInputStream(new FileInputStream(inFile));
//byte[] fileBytes = new byte[(int) inFile.length()];
byte[] fileBytes = new byte[BUF_SIZE];
incomingData = new byte[BUF_SIZE];
double numPktToSend = Math.ceil(inFile.length()*1.0/BUF_SIZE);
//Log.d("CLIENT", "Total packets to be sent = " + numPktToSend);
int sleepCycle = 1;
long sysPackSent = 0;
//long startTxPackets = TrafficStats.getTotalTxPackets();
long startTxPackets = TrafficStats.getUidTxPackets(Process.myUid());
Log.d("CLIENT", "startTxPacks: " + startTxPackets);
long packDrops = 0;
long startTime = System.nanoTime();
long count=0;
long ackRec=0;
int seqNo = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outStream);
while((numBytesRead = inputBuf.read(fileBytes)) != -1) {
//DatagramPacket packet = new DatagramPacket(fileBytes, fileBytes.length);
if (os == null) {
os = new ObjectOutputStream(outStream);
}
Message msg = new Message(++seqNo, fileBytes, false);
os.writeObject(msg);
os.flush();
os.reset();
byte[] data = outStream.toByteArray();
DatagramPacket packet = new DatagramPacket(data, data.length);
clientSocket.send(packet);
numPackSent += 1;
//Log.d("CLIENT", "No of packets sent = " + numPackSent);
sysPackSent = TrafficStats.getUidTxPackets(Process.myUid()) - startTxPackets;
try{
clientSocket.setSoTimeout(5000);
packet = new DatagramPacket(incomingData, incomingData.length);
clientSocket.receive(packet);
String recAck = new String(packet.getData());
ackRec++;
}
catch(Exception e) {
//Log.d("CLIENT", Log.getStackTraceString(e));
}
packDrops = numPackSent - ackRec;
if (packDrops > count) {
sleepCycle = Math.min(16, sleepCycle * 2);
count = packDrops;
Log.d("CLIENT",String.valueOf(sleepCycle) + " :: " + numPackSent);
} else {
sleepCycle = Math.max(sleepCycle - 1, 1);
}
Thread.sleep(sleepCycle);
}
if (numBytesRead == -1) {
fileBytes = "END".getBytes();
Log.d("CLIENT", "Sending END Packet");
clientSocket.send(new DatagramPacket(fileBytes, fileBytes.length));
}
Log.d("CLIENT", "Actual Time elapsed = " + (System.nanoTime() - startTime)/Math.pow(10, 9) + " s");
Log.d("CLIENT", "Total Packets Transmitted = " + Long.toString(sysPackSent));
Log.d("CLIENT", "No of packets dropped = " + String.valueOf(packDrops));
Log.d("CLIENT", "Packets Pushed to Socket = " + numPackSent);
Log.d("CLIENT", "Number of Acknoledgments received " +ackRec);
inputBuf.close();
os.close();
outStream.close();
clientSocket.disconnect();
clientSocket.close();
Log.d("CLIENT", "Sending file.. Complete!!!");
} catch (Exception e) {
Log.d("CLIENT", Log.getStackTraceString(e));
clientSocket.disconnect();
clientSocket.close();
}
return null;
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
clientSocket = new DatagramSocket();
clientSocket.connect(serverAddr, SERVERPORT);
Log.d("CLIENT", "Connection Successful");
} catch (UnknownHostException e1) {
Log.d("CLIENT", "Inside run() UnknownHostEx");
Log.d("CLIENT", Log.getStackTraceString(e1));
} catch (IOException e1) {
Log.d("CLIENT", "Inside run() IOEx");
Log.d("CLIENT", Log.getStackTraceString(e1));
}
}
}
I am getting a few errors at the Server side:
I am receiving the same sequence number for each packet (i.e. 1)
I am not sure about the buffer size for the incoming packet, as I am using 500 bytes at Client side and 1024 at the Sever. And if I take 500 bytes in both the codes I get a End of File exception.
I would really appreciate if you could suggest better ways to implement the same thing!
Thanks :)
Thanks!

Create a ByteArrayOutputStream.
Wrap it in a DataOutputStream
Use DataOutputStream.writeInt() to write the sequence number.
Use write() to write the data.
Construct the DatagramPacket from the byte array returned by the ByteArrayOutputStream.
At the receiver, do exactly the reverse, using the complementary classes and methods in each case. What those are is left as an exercise for the reader.

The simplest method would probably be to a look at the TCP protocol, and stick all the TCP headers into the start of each of your UDP packets.

Related

Dynamic display data TextView

I already got displayed data received from microprocesor via bluetooth. It sends me an 8-bit frame with actual Voltage and Temperature state every second.
The issue is the TextView doesn't displaying actual data. When app loads, the data is displayed and stays like that. One method to refresh data is to load app again.
I got handler and ConnectedThread which code I attach.
All the best from Poland.
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
sb.append(readMessage);
int endOfLineIndex = sb.indexOf(";\r\n");
if (endOfLineIndex > 0) {
String dataInPrint = sb.substring(0, endOfLineIndex);
strDlugosc.setText(dataInPrint);
int dataLenght = dataInPrint.length();
strLenght.setText("ilość otrzymanych znakow =" + String.valueOf(dataLenght));
if (sb.charAt(0) == '9') {
String statusb = sb.substring(8,9);
String temperatura = sb.substring(21, 27);
String napiecie = sb.substring(12, 18);
status.setText("Status :" + statusb);
temp_1.setText("TEMPERATURA = " + temperatura + " *C");
nap_1.setText("NAPIECIE = " + napiecie + " V");
}
}
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep looping to listen for received messages
while (!ConnectedThread.interrupted()) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
I did it before. I used a timer to get data from BlueTooth socket every 1 second
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// get data from socket and set to text view here
}
}, 0, 10000 /** milliseconds **/);

Multicast Android + tethering "Network is unreachable"

Following options resulting shown error
Android App + Multicast + Tethering On + Cell Data Off
If I connected to wifi router, no errors happen. What do I wrong or is android+multicast+tethering impossible?
public class Multicast {
final static String INET_ADDR = "224.0.0.1";
final static int PORT = 8888;
private Context mContext;
public Multicast(Context context) {
mContext = context;
}
public static NetworkInterface getWlanEth() {
final String TAG = "NetworkInterface";
Enumeration<NetworkInterface> enumeration = null;
try {
enumeration = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
NetworkInterface wlan0 = null;
StringBuilder sb = new StringBuilder();
while (enumeration.hasMoreElements()) {
wlan0 = enumeration.nextElement();
sb.append(wlan0.getName() + " ");
if (wlan0.getName().equals("wlan0")) {
return wlan0;
}
}
return null;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void startMulticastServer() {
Thread sendThread = new Thread(new Runnable() {
DatagramSocket serverSocket;
#Override
public void run() {
try {
if (serverSocket == null) {
serverSocket = new DatagramSocket(null);
serverSocket.setReuseAddress(true);
serverSocket.setBroadcast(true);
serverSocket.bind(new InetSocketAddress(PORT));
serverSocket.setSoTimeout(15000);
}
for (int i = 0; i < 5; i++) {
String msg = "Sent message no " + i;
InetAddress group = InetAddress.getByName(INET_ADDR);
DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
msg.getBytes().length, group, PORT);
serverSocket.send(msgPacket);
String TAG = "Multicast-send";
Log.i(TAG, "Socket 1 send msg: " + msg);
Thread.sleep(500);
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
sendThread.start();
}
public void startMulticastClient() {
Thread getThread = new Thread(new Runnable() {
byte[] buf = new byte[256];
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void run() {
//Acquire the MulticastLock
WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
MulticastLock multicastLock = wifi.createMulticastLock("multicastLock");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
// Create a new Multicast socket (that will allow other sockets/programs
// to join it as well.
try {
MulticastSocket clientSocket = new MulticastSocket(PORT);
//Joint the Multicast group.
clientSocket.joinGroup(new InetSocketAddress(InetAddress.getByName(INET_ADDR), PORT), getWlanEth());
clientSocket.setLoopbackMode(true);
while (true) {
// Receive the information and print it.
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(msgPacket);
String msg = new String(msgPacket.getData());
String TAG = "Multicast-get";
Log.i(TAG, "Socket 1 received msg: " +msgPacket.getAddress()+" : "+ InetAddress.getByName(INET_ADDR) + " : " +msg);
}
} catch (IOException ex) {
multicastLock.release();
ex.printStackTrace();
}
multicastLock.release();
}
});
getThread.start();
}
}

client.getInputStream returns null

I am trying to use the WifiDirect demo api to send a recorded audio to another android device but input stream from the socket always returns null.
Any help is much appreciated.
Here are portion of the code
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory(), File.separator + "SuDAB/received/"
+ "sudab-" + System.currentTimeMillis()
+ ".3gp");
File dirs = new File(f.getParent());
if (!dirs.exists()) {
dirs.mkdirs();
}
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
and
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime = System.currentTimeMillis();
if (inputStream == null) {
return false;
}
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime = System.currentTimeMillis() - startTime;
Log.v(WiFiDirectActivity.TAG, "Time taken to transfer all bytes is : " + endTime);
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
this is how i pass the file to be sent to the FileTransferService
mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Allow user to pick an image from Gallery or other
// registered apps
TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
statusText.setText("Sending: " + lastFile);
Log.d(WiFiDirectActivity.TAG, "Intent----------- " + lastFile);
Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
Log.d(WiFiDirectActivity.TAG, "File transfer service created...");
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, lastFile);
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
getActivity().startService(serviceIntent);
}
});
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, lastFile);
should be
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, "file://"+lastFile);
instead.

Socket can be send only once and the Textview is not gathering the information from the server

I had two issues in the program I am making... the thing is that I want to send by a Edittext that information to a server via UDP....the thing is that the program only works the first time I run the program, I mean, if i open the application and write some text, the information is sended to the server, but if I type another thing and press to button so the new information is sended it doesn't work... the other thing is that the TextView is not appending the information, and the server send some info but the application is not gathering that information... so if someone had a clue why is this happening or what I am doing wrong I appreciated any help!... Thanks in advice...
here is the code:
public class MainActivity extends Activity implements View.OnClickListener {
public static final String SERVERIP = "190.99.20.200";
public static final int SERVERPORT = 5153;
public TextView serverResponse;
public EditText messageToSend;
public Button btnSend;
public boolean start;
public Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverResponse = (TextView)findViewById(R.id.textView);
messageToSend = (EditText)findViewById(R.id.editText);
btnSend = (Button)findViewById(R.id.button);
btnSend.setOnClickListener(this);
start = false;
new Thread(new Server()).start();
try{
Thread.sleep(500);
}catch (InterruptedException e){
updatetrack("Error on Server:" + e.getMessage());
}
new Thread(new Client()).start();
handler = new Handler(){
public void handledMessage(Message msg){
String text = (String)msg.obj;
serverResponse.append(text);
}
};
}
public class Client implements Runnable {
#Override
public void run() {
while(start == false)
{
}
try{
Thread.sleep(500);
}catch (InterruptedException e1){
e1.printStackTrace();
}
try{
InetAddress serverAddres = InetAddress.getByName(SERVERIP);
updatetrack("Client:Start connectingn");
DatagramSocket socket = new DatagramSocket();
byte[] buffer;
if(!messageToSend.getText().toString().isEmpty())
{
buffer = messageToSend.getText().toString().getBytes();
}
else
{
buffer = ("Message from android").getBytes();
}
DatagramPacket packet = new DatagramPacket(buffer, buffer.length,serverAddres,SERVERPORT);
updatetrack("Client:Sending" + new String(buffer)+ "'n");
socket.send(packet);
updatetrack("Client: Messange sentn");
updatetrack("Client: Succed!n ");
socket.close();
}catch (Exception e){
updatetrack("Client:Error!n" + e.getMessage());
}
}
}
public class Server implements Runnable{
#Override
public void run() {
while (start == false)
{
}
try{
InetAddress serverAddress = InetAddress.getByName(SERVERIP);
updatetrack("nServer: Start connectingn");
DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddress);
byte[] buffer = new byte[17];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
updatetrack("Server: Receivingn");
socket.receive(packet);
updatetrack("Server: Message received:" + new String(packet.getData())+"'n");
updatetrack("Server : Succed!n");
}catch (Exception e){
updatetrack("Server: Error!n"+ e.getMessage());
}
}
}
public void onClick(View view)
{
start = true;
}
public void updatetrack(String s)
{
Message msg = new Message();
String textTochange = s;
msg.obj = textTochange;
handler.sendMessage(msg);
}
}
The run method in your server class will run only once.
while(start == false){
}
This while loop will continue to loop until you call the onClick method, at which point the rest of the code in the run() method is executed, and the server thread killed. You need to rearrange your code a little, and place it inside the while loop:
public void run() {
while (true){
try{
InetAddress serverAddress = InetAddress.getByName(SERVERIP);
updatetrack("nServer: Start connectingn");
DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddress);
byte[] buffer = new byte[17];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
updatetrack("Server: Receivingn");
socket.receive(packet);
updatetrack("Server: Message received:" + new String(packet.getData())+"'n");
updatetrack("Server : Succed!n");
}catch (Exception e){
updatetrack("Server: Error!n"+ e.getMessage());
}
}
}

Android Audio Track Play with noise

I am working on a peer to peer to voice call application in Android for my college project. I found sample code for streaming the mic audio through UDP. That code will help me to stream the WAV file through UDP. But it doesn't play some files properly. And also that code doesn't stream mic audio.
Please help me.
public class UdpStream extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.udpstream);
Button btnSend = (Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "btnSend clicked");
SendAudio();
}
});
Button btnRecv = (Button)findViewById(R.id.btnRecv);
btnRecv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "btnRecv clicked");
RecvAudio();
}
});
Button btnStrmic = (Button)findViewById(R.id.btnStrmic);
btnStrmic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "btnStrmic clicked");
SendMicAudio();
}
});
}
static final String LOG_TAG = "UdpStream";
static final String AUDIO_FILE_PATH = "/sdcard/1.wav";
static final int AUDIO_PORT = 2048;
static final int SAMPLE_RATE = 8000;
static final int SAMPLE_INTERVAL = 20; // milliseconds
static final int SAMPLE_SIZE = 2; // bytes per sample
static final int BUF_SIZE = SAMPLE_INTERVAL*SAMPLE_INTERVAL*SAMPLE_SIZE*2;
protected String host="localhost";
public void RecvAudio()
{
Thread thrd = new Thread(new Runnable() {
#Override
public void run()
{
Log.e(LOG_TAG, "start recv thread, thread id: "
+ Thread.currentThread().getId());
AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC,
SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, BUF_SIZE,
AudioTrack.MODE_STREAM);
track.play();
try
{
DatagramSocket sock = new DatagramSocket(AUDIO_PORT);
byte[] buf = new byte[BUF_SIZE];
while(true)
{
DatagramPacket pack = new DatagramPacket(buf, BUF_SIZE);
sock.receive(pack);
Log.d(LOG_TAG, "recv pack: " + pack.getLength());
track.write(pack.getData(), 0, pack.getLength());
}
}
catch (SocketException se)
{
Log.e(LOG_TAG, "SocketException: " + se.toString());
}
catch (IOException ie)
{
Log.e(LOG_TAG, "IOException" + ie.toString());
}
} // end run
});
thrd.start();
}
Toast toast;
int port=3008;
public void SendAudio()
{
toast=Toast.makeText(getApplicationContext(), port + " : " + host , Toast.LENGTH_SHORT);
Thread thrd = new Thread(new Runnable() {
#Override
public void run()
{
Log.e(LOG_TAG, "start send thread, thread id: "
+ Thread.currentThread().getId());
long file_size = 0;
int bytes_read = 0;
int bytes_count = 0;
File audio = new File(AUDIO_FILE_PATH);
FileInputStream audio_stream = null;
file_size = audio.length();
byte[] buf = new byte[BUF_SIZE];
try
{
EditText d= (EditText) findViewById(R.id.txttohost);
host=d.getText().toString();
if(host=="")
{
port=2048;
host="localhost";
}
port=2048;
InetAddress addr = InetAddress.getByName(host);
toast.setText(port + " : " + addr.toString());
toast.show();
DatagramSocket sock = new DatagramSocket();
audio_stream = new FileInputStream(audio);
while(bytes_count < file_size)
{
bytes_read = audio_stream.read(buf, 0, BUF_SIZE);
DatagramPacket pack = new DatagramPacket(buf, bytes_read,
addr, port);
sock.send(pack);
bytes_count += bytes_read;
Log.d(LOG_TAG, "bytes_count : " + bytes_count);
Thread.sleep(SAMPLE_INTERVAL, 0);
}
}
catch (InterruptedException ie)
{
Log.e(LOG_TAG, "InterruptedException");
}
catch (FileNotFoundException fnfe)
{
Log.e(LOG_TAG, "FileNotFoundException");
}
catch (SocketException se)
{
Log.e(LOG_TAG, "SocketException");
}
catch (UnknownHostException uhe)
{
Log.e(LOG_TAG, "UnknownHostException");
}
catch (IOException ie)
{
Log.e(LOG_TAG, "IOException");
}
} // end run
});
thrd.start();
}
public void SendMicAudio()
{
Thread thrd = new Thread(new Runnable() {
#Override
public void run()
{
Log.e(LOG_TAG, "start SendMicAudio thread, thread id: "
+ Thread.currentThread().getId());
AudioRecord audio_recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, SAMPLE_RATE,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
AudioRecord.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT) * 10);
int bytes_read = 0;
int bytes_count = 0;
byte[] buf = new byte[BUF_SIZE];
try
{
InetAddress addr = InetAddress.getLocalHost();
DatagramSocket sock = new DatagramSocket();
while(true)
{
bytes_read = audio_recorder.read(buf, 0, BUF_SIZE);
DatagramPacket pack = new DatagramPacket(buf, bytes_read,
addr, AUDIO_PORT);
sock.send(pack);
bytes_count += bytes_read;
Log.d(LOG_TAG, "bytes_count : " + bytes_count);
Thread.sleep(SAMPLE_INTERVAL, 0);
}
}
catch (InterruptedException ie)
{
Log.e(LOG_TAG, "InterruptedException");
}
// catch (FileNotFoundException fnfe)
// {
// Log.e(LOG_TAG, "FileNotFoundException");
// }
catch (SocketException se)
{
Log.e(LOG_TAG, "SocketException");
}
catch (UnknownHostException uhe)
{
Log.e(LOG_TAG, "UnknownHostException");
}
catch (IOException ie)
{
Log.e(LOG_TAG, "IOException");
}
} // end run
});
thrd.start();
}
}
As for as concern with my question....
The Solution is Always while playing the Audio through out speaker will cause Some noise....
So i found the following two solution to fix that...
1) Play the audio through ear piece
audio_service.setSpeakerphoneOn(false);
audio_service.setMode(AudioManager.MODE_IN_CALL);
audio_service.setRouting(AudioManager.MODE_NORMAL,AudioManager.ROUTE_EARPIECE,
AudioManager.ROUTE_ALL);
2) Next way to do use Some Audio Codec for encoding and Decoding Your Audio to play that in noiseless..

Categories

Resources