client Windows and Android server over USB - android

I'm making an Android App to communicate with a computer windows.
I found that it must be easy to do that by forwarding the port with ADB commands.
So i try to make a client/server connection over USB but i have some problems
my server on Windows:
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("EchoClient.main()");
Socket client = null;
// initialize server socket
try {
server = new ServerSocket(38300);
server.setSoTimeout(TIMEOUT * 1000);
// attempt to accept a connection
client = server.accept();
Globals.socketOut = new PrintStream(client.getOutputStream());
Globals.socketIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
// Globals.socketIn.YY
} catch (SocketTimeoutException e) {
// print out TIMEOUT
connectionStatus = "Connection has timed out! Please try again";
System.out.println(connectionStatus);
} catch (IOException e) {
System.out.println("error"+ e);
} finally {
// close the server socket
try {
if (server != null)
server.close();
} catch (IOException ec) {
System.out.println("Cannot close server socket"+ ec);
}
}
if (client != null) {
System.out.println("connected");
}
}
public static class Globals {
private static String typeOfTransmission ;
static PrintStream socketOut = null;
static BufferedReader socketIn = null;
public static synchronized String getTypeTransmission(){
return typeOfTransmission;
}
public static synchronized void setTypeTransmission(String s){
typeOfTransmission = s;
}
}
}
android APP client
private Runnable initializeConnection = new Thread() {
public void run() {
Socket client = null;
// initialize server socket
try {
Log.d("ip",getLocalIpAddress());
client = new Socket(getLocalIpAddress(), 38300);
Globals.socketIn = new Scanner(new InputStreamReader(
client.getInputStream()));
Globals.socketOut = new PrintWriter(client.getOutputStream());
// Globals.socketIn.YY
} catch (SocketTimeoutException e) {
// print out TIMEOUT
connectionStatus = "Connection has timed out! Please try again";
mHandler.post(showConnectionStatus);
} catch (IOException e) {
Log.e(TAG, "" + e);
} finally {
// close the server socket
try {
if (server != null)
server.close();
} catch (IOException ec) {
Log.e(TAG, "Cannot close server socket"+ ec);
}
}
if (client != null) {
Globals.connected = true;
// print out success
connectionStatus = "Connection was succesful!";
Log.d(TAG, "connected!");
mHandler.post(showConnectionStatus);
while (Globals.socketIn.hasNext()) {
socketData = Globals.socketIn.next();
mHandler.post(socketStatus);
}
}
}
};
public String getLocalIpAddress(){
try{
for(Enumeration<NetworkInterface> en =NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
NetworkInterface intf = en.nextElement();
for(Enumeration<InetAddress> enumIpAddress= intf.getInetAddresses();enumIpAddress.hasMoreElements();){
InetAddress inetAddress = enumIpAddress.nextElement();
if (!inetAddress.isLoopbackAddress()){
return inetAddress.getHostAddress().toString();
}
}
}
}catch(SocketException ex){
Log.e("ServerActivity",ex.toString());
}
return null;
}
Logger
01-29 11:43:49.640: D/ip(2981): fe80::a806:ff:fec6:d3d%p2p0
01-29 11:43:49.650: E/Connection(2981): java.net.ConnectException: failed to connect to /fe80::a806:ff:fec6:d3d%p2p0%4 (port 38300): connect failed: ECONNREFUSED (Connection refused)
thank you

Related

java.net.ConnectException Connection Refused

I am stucked at a problem when trying to implement a server/client application for Android.
I implemented a server class which I initialize through the constructor first and then I start an async task for running it.
Here is the server class:
public class Server {
RestaurantTables activity;
ServerSocket serverSocket;
String message = "";
Handler updateConversationHandler;
//static final int socketServerPORT = 8080;
static final int socketServerPORT = 0; // 0 = take any free port
public Server(RestaurantTables activity) {
this.activity = activity;
//Thread socketServerThread = new Thread(new SocketServerThread(this.activity.getHandler()));
updateConversationHandler = new Handler();
map = new HashMap();
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SocketConnectAsyncTask atSockConn = new SocketConnectAsyncTask();
atSockConn.execute();
}
public int getPort() {
return serverSocket.getLocalPort();
}
public void closeSocket() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketConnectAsyncTask extends AsyncTask<Void, Void, Void>
{
int count = 0;
Handler mHandler;
Socket socket;
#Override
//public void run() {
protected Void doInBackground(Void... params) {
try {
/*// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
*/
while (true) {
// block the call until connection is created and return
// Socket object
socket = serverSocket.accept();
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ReceiveMessage atRecMsg = new ReceiveMessage(socket, this.mHandler);
atRecMsg.execute();
}
}
class ReceiveMessage extends AsyncTask<Void, Void, Void> {
private Socket clientSocket;
private Handler mHandler;
private BufferedReader input;
public ReceiveMessage(Socket clientSocket, Handler mHandler)
{
this.clientSocket = clientSocket;
this.mHandler = mHandler;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... params) {
while(true) {
try {
String read = input.readLine();// blocking
Message msg = Message.obtain();
msg.obj = read; // Put the string into Message, into "obj" field.
msg.setTarget(mHandler); // Set the Handle
System.out.println("Here is what I read: " + read);
//updateConversationHandler.post(new updateUIThread(read));
//mHandler.sendMessage();
msg.sendToTarget(); //Send the message
try {
OutputStream outputStream = clientSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print("OK");
printStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
//return null;
}
}
public 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 = inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
The call of the server class looks like:
myServer = new Server (this); // this = activity
So I think the server is running then. After trying to connect from the client with following call...
Client myClient = new Client(sServerIpAddress, sServerPort, Commands.this);
... I get the following exception:
W/System.err: java.net.ConnectException: failed to connect to /192.168.200.2 (port 47803) from /:: (port 48982): connect failed: ECONNREFUSED (Connection refused)
W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:138)
W/System.err: at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:129)
W/System.err: at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:356)
W/System.err: at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
W/System.err: at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
W/System.err: at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
W/System.err: at java.net.Socket.connect(Socket.java:616)
W/System.err: at java.net.Socket.connect(Socket.java:565)
W/System.err: at java.net.Socket.<init>(Socket.java:445)
W/System.err: at java.net.Socket.<init>(Socket.java:248)
W/System.err: at emu.apps.com.jollybell.Client.doInBackground(Client.java:45)
W/System.err: at emu.apps.com.jollybell.Client.doInBackground(Client.java:20)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
W/System.err: at java.lang.Thread.run(Thread.java:764)
W/System.err: Caused by: android.system.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
W/System.err: at libcore.io.Linux.connect(Native Method)
W/System.err: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:126)
W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:152)
W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:130)
W/System.err: ... 17 more
Honestly I have no clue what is going wrong, even after searching for hours in all possible forums.
If it helps, here is the client class:
class Client extends AsyncTask<String, Void, String> {
public interface ServerResponse {
void serverResultReceived(String output);
}
String sIpAddress, sPort, response;
private Socket socket;
private PrintWriter out;
public ServerResponse delegate = null;
public Client(String sIpAddress, String sPort, ServerResponse delegate)
{
this.sIpAddress = sIpAddress;
this.sPort = sPort;
this.delegate = delegate;
}
//#Override
//public void run() {
#Override
protected String doInBackground(String... params) {
try {
InetAddress serverAddr = InetAddress.getByName(this.sIpAddress);
socket = new Socket(serverAddr, Integer.parseInt(this.sPort));
// First send command
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.print(params[0]);
// ... then wait for answer
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice: inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
delegate.serverResultReceived(result);
}
}
So folks. Been some time ago, but I found out how to resolve my problem.
First of all, in the client there is a small problem. I am writing with "out.print" function and then waiting in the server with function "readLine()".
readLine expects the end of a line so either the string should be send with a final "/n" or function "println" has to be used instead of print.
Second, When I started 2 android devices, they could not communicate to each other. I still did not find out why, but using the same device to run the server and the client application worked for me.

My bluetooth connection unexpectedly closed in Android

java.io.IOException: bt socket closed, read return: -1
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:434)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.InputStreamReader.read(InputStreamReader.java:231)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.BufferedReader.readLine(BufferedReader.java:397)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at com.example.lg.scoreboardapp.MainActivity$ConnectThread.run(MainActivity.java:336)
Sometimes in my app, client unexpectedly closed.
I don't know why......
I have three diveces. one devices is server. others are client.
They are connected well, but one client was closed. other client is still open.
Please give me the solution...!!
It's MainActivitity.. 336Lineenter code here
while(socket != null){
i++;
Log.d("MAinActivity","-----------------"+i+"-----------------------------");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final String str1 = in.readLine(); //<<---Line 336
Log.d("MainActivity","--------------------------------------"+str1+i);
json1 = str1;
parse();
}
It's ConnectThread client
private class ConnectThread extends Thread {
private BluetoothSocket socket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Toast.makeText(MainActivity.this, "연결에 실패하였습니다.\n다시 시도하여 주세요", Toast.LENGTH_SHORT).show();
e.printStackTrace();
//mkmsg("Client connection failed: "+e.getMessage().toString()+"\n");
}
socket = tmp;
}
public void run() {
// mkmsg("Client running\n");
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket.connect();
} catch (IOException e) {
//mkmsg("Connect failed\n");
e.printStackTrace();
try {
socket.close();
socket = null;
} catch (IOException e2) {
//mkmsg("unable to close() socket during connection failure: "+e2.getMessage().toString()+"\n");
socket = null;
e2.printStackTrace();
}
// Start the service over to restart listening mode
}
// If a connection was accepted
if (socket != null) {
//mkmsg("Connection made\n");
//mkmsg("Remote device address: "+socket.getRemoteDevice().getAddress().toString()+"\n");
//Note this is copied from the TCPdemo code.
try {
int i=0;
while(socket != null){
i++;
Log.d("MAinActivity","-----------------"+i+"-----------------------------");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final String str1 = in.readLine();
Log.d("MainActivity","--------------------------------------"+str1+i);
json1 = str1;
parse();
}
Log.d("MainActivity_341Line","socket is null.......... check this");
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"MainActivity_341Line socket is null.......... check this",Toast.LENGTH_LONG);
}
});
} catch(Exception e) {
//mkmsg("Error happened sending/receiving\n");
e.printStackTrace();
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Error happened sending/receiving\\n",Toast.LENGTH_LONG);
Log.d("MainActivity_341Line","Error happened sending/receiving");
}
});
try {
socket.close();
socket = null;
} catch (IOException e2) {
//mkmsg("unable to close() socket during connection failure: "+e2.getMessage().toString()+"\n");
socket = null;
Log.d("MainActivity_341Line","Error happened "+e2);
e2.printStackTrace();
}
}
} else {
//mkmsg("Made connection, but socket is null\n");
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Made connection, but socket is null\\n",Toast.LENGTH_LONG);
}
});
}
}
public void cancel() {
try {
socket.close();
Toast.makeText(MainActivity.this, "채점기기와의 연결이 끝났습니다", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "채점기기와의 연결이 끝났습니다", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
Try to replace your run() method in your ConnectThread to this:
public void run()
{
Log.e(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
mAdapter.cancelDiscovery();
try
{
mmSocket.connect();
}
catch (IOException e)
{
try
{
Log.e(TAG,"Trying fallback...");
mmSocket = (BluetoothSocket)
mmDevice.getClass()
.getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mmDevice, 2);
mmSocket.connect();
Log.e(TAG,"Connected");
}
catch (Exception e2)
{
Log.e(TAG, "Couldn't establish Bluetooth connection!");
try
{
mmSocket.close();
}
catch (IOException e3)
{
Log.e(TAG, "unable to close() " + " socket during connection failure", e3);
}
connectionFailed();
return;
}
}
synchronized (BluetoothHelper.this)
{
mConnectThread = null;
}
connected(mmSocket, mmDevice);
}

how to send data from Group owner to client with wifi p2p

I tested many ways and finally asked this question. as many of articles mentioned in wifi-direct all clients know group owner's IP and can use this ip to send a message and group owner will save clients ip address. but I can't send a message from group owner to client like that client sent first time. I faced with this error's:
first:
failed to connect to /192.168.49.24 (port 8988) after 5000ms: isConnected failed:
EHOSTUNREACH (No route to host).
after change code:
first error + bind failed: EADDRINUSE (Address already in use).
My AsyncTask to retrieve :
#Override
protected String doInBackground(Void... params) {
ServerSocket serverSocket = null;
Socket client = null;
DataInputStream inputstream = null;
try {
serverSocket = new ServerSocket(8988);
client = serverSocket.accept();
inputstream = new DataInputStream(client.getInputStream());
String str = inputstream.readUTF();
String IP = client.getInetAddress().toString();
serverSocket.close();
return IP+"+"+str;
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}finally{
if(inputstream != null){
try{
inputstream.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(client != null){
try{
client.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(serverSocket != null){
try{
serverSocket.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
}
}
and my IntentService to send messages:
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_IP)) {
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Log.e("DAVUD","Host:"+ host);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
Log.e("DAVUD","Port:"+ port);
DataOutputStream stream = null;
try {
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
stream = new DataOutputStream(socket.getOutputStream());
String str = intent.getStringExtra("message");
stream.writeUTF(str);
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
and some other codes I tested... There is another question asked same this but not answered(android-wifi-direct-how-to-send-data-from-group-owner-to-the-clients) this project based on wifiDirectDemo Simple. Please help I really need it.
After one year I sew my question again. the problem was not about wifi or connection. it's about string parsing. where a line in doInBackground is:
return IP+"+"+str
and in onPostExecute I parsed and get ip from returned string; but parse code was not correct. so returns:
192.168.49.24
instead of:
192.168.49.241
where two of them is valid ips I am not thought parse logic had problem. I changed code and used String[] instead of String.

ServerSocket closing itself in AsyncTask [Android Wifi P2P Manager ]

I am developing a android wifi -chat application .
Bit of Info about my app :
->A device calls startserver() to act as a server ,another device calls start client() to act as a client
What works:
->A Client can successfully send the data for the first time to the client, but not again and again
->I need to call startserver() again on first device , so that client can send data again .
The startserver() calls this Async task ,the following is its DoinBackgroundMethod
protected String doInBackground(Void... params) {
ServerSocket serverSocket = null;
try {
while(true) {
serverSocket = new ServerSocket(PORT);
Socket client = serverSocket.accept();
StartMSG(client);
}
} catch (IOException e) {
return null;
} finally {
try {
chatclient.changeserverrunning(false);
if (serverSocket == null) {
} else {
serverSocket.close();
}
return null;
} catch (Exception e) {
}
}
//return null;
}
protected void StartMSG(Socket client){
try {
InputStream inputstream = client.getInputStream();
ObjectInputStream ois = new ObjectInputStream(inputstream);
Message m = null;
try {
m = (Message) ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (m != null) {
if (m.gettype() == 1) {
final String my_msg = m.getMessage();//Toast msg afterwards
}
}catch (Exception e){
}
}
Client Side Code :
It is started when the client hits send button and calls start client method .in which It sets up the Ip values before and bundles them and calls the message sending part as a Intent Service called FileTransferService
Its code is (abstracted) :
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if(socket==null){
socket = new Socket();
}
if (intent.getAction().equals(ACTION_SEND_FILE)) {
final String msg_type=intent.getExtras().getString(MESSAGE_TYPE);
String host = intent.getExtras().getString(EXTRAS_ADDRESS);
int port = intent.getExtras().getInt(EXTRAS_PORT);
try {
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Message m = (Message) intent.getExtras().getSerializable(MESSAGE_INTENT_STR);
final String my_message=m.getMessage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(m);
oos.flush();
oos.close();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
OutputStream stream = socket.getOutputStream();
ChatClient.copyFile(is, stream);
} catch (IOException e) {
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
//socket.close();
} catch (Exception e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
You should try https://github.com/tavendo/AutobahnAndroid and run the client from a service, from an asyntask it will always end up finishing.

Android: StreamProxy not working on Nexus4/5 with Android 5.x

Here is a source of StreamProxy I used for my project
public class StreamProxy implements Runnable {
private static final String LOG_TAG = "Stream proxy: %s";
private int port = 0;
private boolean isRunning = true;
private ServerSocket socket;
private Thread thread;
public StreamProxy() {
init();
start();
}
public int getPort() {
return port;
}
public String getProxyUrl(String uri, String tag) {
return String.format("http://127.0.0.1:%d/%s", getPort(), uri);
}
private void init() {
try {
socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[]{127, 0, 0, 1}));
socket.setSoTimeout(5000);
port = socket.getLocalPort();
Timber.d(LOG_TAG, "port " + port + " obtained");
} catch (IOException e) {
Timber.e(e, "Error initializing server");
}
}
private void start() {
if (socket == null) {
throw new IllegalStateException("Cannot start proxy; it has not been initialized.");
}
thread = new Thread(this);
thread.start();
}
public void stop() {
isRunning = false;
if (thread == null) {
throw new IllegalStateException("Cannot stop proxy; it has not been started.");
}
thread.interrupt();
try {
thread.join(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void run() {
Timber.d(LOG_TAG, "running");
while (isRunning) {
try {
Socket client = socket.accept();
if (client == null) {
continue;
}
Timber.d(LOG_TAG, "client connected");
client.setKeepAlive(false);
readRequest(client);
} catch (SocketTimeoutException e) {
} catch (IOException e) {
Timber.e(e, "Error connecting to client");
}
}
Timber.d(LOG_TAG, "Proxy interrupted. Shutting down.");
}
#Nullable
private void readRequest(Socket client) throws IOException {
InputStream is;
String firstLine;
try {
is = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
firstLine = reader.readLine();
} catch (IOException e) {
Timber.e(LOG_TAG, "Error parsing request", e);
return;
}
if (firstLine == null) {
Timber.i(LOG_TAG, "Proxy client closed connection without a request.");
return;
}
StringTokenizer st = new StringTokenizer(firstLine);
st.nextToken();
String uri = st.nextToken().substring(1);
Timber.d(LOG_TAG, uri);
processRequest(client, uri, "");
}
#Nullable
private HttpURLConnection download(String path) throws IOException {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage());
}
return connection;
}
private void processRequest(Socket client, String url, String tag)
throws IllegalStateException, IOException {
Timber.d(LOG_TAG, "processing");
HttpURLConnection realResponse = download(url);
if (realResponse == null) {
return;
}
InputStream data = realResponse.getInputStream();
socketWriter.setClient(client);
try {
int readBytes;
Timber.d(LOG_TAG, "writing data to client");
// Start streaming content.
byte[] buff = new byte[1024 * 8];
while (isRunning && (readBytes = data.read(buff)) != -1) {
client.getOutputStream().write(buff, 0, readBytes)
}
Timber.d(LOG_TAG, "end writing data");
} catch (IOException e) {
Timber.e(e, "Error data transfer to client");
} finally {
Timber.d(LOG_TAG, "finally block");
if (data != null) {
data.close();
}
}
}
}
It works perfectly on Android <5.0 but on Android 5.0.+ I have following error with using MediaExtractor(http://developer.android.com/reference/android/media/MediaExtractor.html)
NuCachedSource2﹕ source returned error -1, 10 retries left
NuCachedSource2﹕ source returned error -1, 9 retries left
...
And no error messages when using Mediaplayer just few quiet retries.
Maybe for Android 5 there is another way for audio streaming with caching?
Stream proxy working well actually. All errors I get from MediaExtractor was about m4a container. For most files packed in m4a format, there is no way to play it via stream by using components from Android SDK. Except some roms on Samsung, LG and some other manufactures that has this feature.

Categories

Resources