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

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.

Related

Problem regarding receiving files from android device into the esp8266

I've been working on a project where i would send a file from the android app i wrote to my esp8266; the esp8266 then will write the file onto the SD card. but when esp receives the file for example a .jpg, it's all garbled and noisy.
and if i receive a .txt file it will always add a (¬í ur [B¬óøTà xp ¬) at the beginning, regardless of what method i use.
Here's my android code:
(Server thread)
Socket mySocket = null;
ServerSocket serverSocket = null;
class ServerThread implements Runnable{
int serverPort;
public ServerThread(int serverPort){
this.serverPort = serverPort;
}
#Override
public void run() {
try {
serverSocket = new ServerSocket(serverPort);
mySocket = serverSocket.accept();
output = new PrintWriter(mySocket.getOutputStream());
input = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
Log.i("connection", "server");
runOnUiThread(new Runnable() {
#Override
public void run() {
connection_state = true;
LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView thisText = new TextView(MainActivity.this);
thisText.setId(append);
thisText.setText("Server port: " + 8080 + " ... A client just made connection");
thisText.setTextSize(20);
thisText.setBackgroundColor(Color.rgb(25, 24, 24));
thisText.setTextColor(Color.rgb(0, 100, 0));
append++;
thisText.setGravity(20);
thisText.setLayoutParams(textParams);
myTexts.addView(thisText);
}
});
new Thread(new ReceiveStringThread()).start();
} catch (IOException e) {
e.printStackTrace();
Log.i("connection", "couldn't establish connection");
} finally {
try {
if (socket != null)
socket.close();
if (serverSocket != null)
serverSocket.close();
}catch (IOException e){
e.getStackTrace();
}
}
}
}
Send file thread:
class SendFileThread implements Runnable{
String filePath;
SendFileThread(String filePath) {
this.filePath = filePath;
}
#Override
public void run() {
if(connection_state) {
File findFile = new File(filePath);
byte[] sendIt = new byte[(int) findFile.length()];
try {
BufferedInputStream bufferFile = new BufferedInputStream(new FileInputStream(findFile));
bufferFile.read(sendIt, 0, sendIt.length);
ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
oos.writeObject(sendIt);
oos.flush();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "File was sent successfully. size: " +
(int) findFile.length() + " bytes", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.getStackTrace();
}finally {
try {
mySocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
and here's my arduino code for esp8266:
#include <ESP8266WiFi.h>
#include <SD.h>
#ifndef STASSID
#define STASSID "ESP_CLIENT"
#define STAPSK "client-1234"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "192.168.1.103";
const uint16_t port = 8080;
boolean connectionStatus = false;
byte buffer_array[10] = {'0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00'};
int num_read;
WiFiClient client;
void setup() {
Serial.begin(57600);
//.................Initiate SD card................//
if(!SD.begin(SS)){
Serial.println("SD card initialization failed!");
return;
}else{
Serial.println("SD card initialized successfully");
}
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
char *printBytes(byte *bytes) {
char bytesStr[10];
sprintf(bytesStr, "%02X", *bytes);
Serial.print("byte: ");
Serial.println(bytesStr);
return bytesStr;
}
void loop() {
if(!connectionStatus){
Serial.print("connecting to ");
Serial.print(host);
Serial.print(':');
Serial.println(port);
if (!client.connect(host, port)) {
Serial.println("********************************************Connection failed************************************************");
connectionStatus = false;
delay(1000);
return;
}else{
Serial.println("********************************************Connection established with server***********************************************");
connectionStatus = true;
}
Serial.println("sending data to server");
if (client.connected()) {
client.println("hello from ESP8266");
}
}
if(client.available()){
Serial.println("Receiving...");
num_read = client.readBytesUntil('\n',buffer_array, 10);
Serial.println("bytes read: " + (String)num_read);
printBytes(buffer_array);
File appendSD = SD.open("/testESP32.txt", FILE_WRITE);
if(!appendSD){
Serial.println("not found");
return;
}else{
Serial.println("Writing byte to file...");
appendSD.write(buffer_array, num_read);
appendSD.close();
}
}
}
and regardless of which mode i put them into, whether it'll be esp as server and android device as client or reverse, it won't make a difference at all.
anyone knows how to fix this?
i modified the SendFileThread as below but it only worked for sending .txt files correctly. but sending image files like .jpg problem still stands.
class SendFileThread implements Runnable{
String filePath;
SendFileThread(String filePath) {
this.filePath = filePath;
}
#Override
public void run() {
if(connection_state) {
File findFile = new File(filePath);
byte[] sendIt = new byte[(int) findFile.length()];
try {
BufferedInputStream bufferFile = new BufferedInputStream(new FileInputStream(findFile));
bufferFile.read(sendIt, 0, sendIt.length);
OutputStream os= mySocket.getOutputStream();
os.write(sendIt);
os.flush();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "File was sent successfully. size: " +
(int) findFile.length() + " bytes", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.getStackTrace();
}finally {
try {
mySocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
}
}
}
and i wanna be able to send all kinds of data like .pdf .doxs as well and ObjectOutputStream sends all this kinds of files just fine if although i'm sending them to another android phone not esp8266
SOLVED: i used
client.read(buffer_array, 10);
for image files instead of
client.readBytesUntil('\n', buffer_array, 10);
and in android changed
ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
oos.writeObject(sendIt);
to
OutputStream os= mySocket.getOutputStream();
os.write(sendIt);
and it finally worked for all types of files!

Android - Connect to socket in separate thread

I am trying to create a very-very simple server-client application in Android.
The server is running on my pc, it was written in python. (just a simple while (true) loop which receives a string and responses with an other string.)
The problem is in the Android client. So i tried to create a singleton class in a separate thread, which:
create the socket
connect to the socket
is reachable from other activites
write to socket
read from socket
I try to write and read from an other asynctask.
It is working until i try to write to the socket again. (1 write is ok, any other attempts are failed.) I do not get any exception, i checked if the socket closed or the writer null, etc. The message just not wrote to the socket.
What's wrong with this solution? :/
Could you please help me?
Here is the thread:
public class ConnectThread extends Thread
{
// singleton Part
private static class ThreadHolder {
static final ConnectThread instance = new ConnectThread();
}
public static synchronized ConnectThread getInstance(){
if(ThreadHolder.instance == null)
Log.d("mytag", "NEW INSTANCE CREATED");
// return (ThreadHolder.instance == null) ? ThreadHolder.instance = new ConnectThread() : ThreadHolder.instance;
return ThreadHolder.instance;
}
private ConnectThread(){
}
// implementation part
private Socket mSocket;
private BufferedWriter socketWriter;
private BufferedReader socketReader;
public Socket getSocket() {
return mSocket;
}
public void WriteToSocket(String msg)
{
try{
if(!(mSocket.isClosed()))
{
Log.d("mytag", "Writing to socket");
if(socketWriter == null)
Log.d("mytag", "Writer closed - in write to socket");
socketWriter.write(msg);
socketWriter.flush();
}else
Log.d("mytag", "CANT write to socket");
}catch(IOException e)
{
e.printStackTrace();
Log.d("mytag", e.toString());
}
}
public String ReadFromSocket()
{
try
{
if(!(mSocket.isClosed())) {
Log.d("mytag", "Reading from socket");
if(socketReader == null)
{
Log.d("mytag", "Reader closed - in read from socket");
}
return socketReader.readLine();
}else
{
Log.d("mytag", "CANT from socket");
return null;
}
}catch (IOException e)
{
e.printStackTrace();
return null;
}
}
#Override
public void run() {
try
{
mSocket = new Socket();
mSocket.setKeepAlive(true);
try
{
mSocket.setTcpNoDelay(true);
}
catch (SocketException e)
{
}
mSocket.connect(new InetSocketAddress("192.168.0.128", 8888), 2000);
if(!(mSocket.isClosed()))
{
Log.d("mytag", "SOCKET IS RUNNING");
socketWriter = new BufferedWriter(new OutputStreamWriter(this.mSocket.getOutputStream()));
socketReader = new BufferedReader(new InputStreamReader(this.mSocket.getInputStream()));
if(socketWriter == null)
{
Log.d("mytag", "WRITER NOT CREATED");
}else
Log.d("mytag", "WRITER READY");
if(socketReader == null)
{
Log.d("mytag", "READER NOT CREATED");
}else
Log.d("mytag", "READER READY");
}
}catch (IOException e)
{
e.printStackTrace();
}
}
}
And here are the attempts to read, write:
#Override
protected Void doInBackground(Void... params)
{
PrintDebugMsg("do in background");
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Checking network availability...");
//progressDialog.setTitle("Checking network availability...");
//check network:
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(parentContext.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnected())
{
networkAvail = true;
response += "| Network available |";
}
PrintDebugMsg("do in background 2");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
changeStatusImg(imgvNetworkStatus, networkAvail?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Pinging server");
//progressDialog.setTitle("Pinging server...");
//check server status
try {
PrintDebugMsg("do in background 3");
if(!(ConnectThread.getInstance().getSocket().isClosed()))
{
ConnectThread.getInstance().WriteToSocket(PING_FROM_DROID);
String line = "";
line = ConnectThread.getInstance().ReadFromSocket();
if(line.equals(PING_ACK))
{
serverAvail = true;
response += " | pinged |";
PrintDebugMsg("do in background 4", true);
}
}
else{
response += " | NOT pinged |";
PrintDebugMsg("do in background 5", true);
throw new UnknownHostException();
}
PrintDebugMsg("do in background 6", true);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response += " | UnknownHostException: " + e.toString() + " - during server check |";
PrintDebugMsg("do in background 7", true);
} finally{
PrintDebugMsg("do in background 9", true);
if(ConnectThread.getInstance().getSocket() != null){
}
}
PrintDebugMsg("do in background 10", true);
if(serverAvail)
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
changeStatusImg(imgvServerStatus, serverAvail?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Connectiong to server...");
//connect to server:
try {
PrintDebugMsg("do in background 11",true);
//socket = new Socket(dstAddress, dstPort);
//socket = ConnectThread.getInstance().getSocket();
PrintDebugMsg("do in background 12",true);
if(!(ConnectThread.getInstance().getSocket().isClosed())) {
PrintDebugMsg("do in background 13",true);
PrintDebugMsg("do in background 14",true);
PrintDebugMsg("do in background 15",true);
ConnectThread.getInstance().WriteToSocket(CONN_REQ_FROM_DROID);
String line = "";
line = ConnectThread.getInstance().ReadFromSocket();
PrintDebugMsg("conn line = " + line, true);
if(line != null && line.equals(CONN_ACK))
{
connected = true;
response += "| connected |";
PrintDebugMsg("do in background 12");
}
}else
{
response += "| NOT connected |";
PrintDebugMsg("do in background 13");
throw new UnknownHostException();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response += " | UnknownHostException: " + e.toString() + " - during connecting |";
}finally{
PrintDebugMsg("connection finished");
}
if(connected) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
changeStatusImg(imgvConnectionStatus, connected?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------
------------
return null;
}
The "util" functions:
private void PrintDebugMsg(String msg, boolean b)
{
if(b)
Log.d("mytag", msg);
}
private void changeProgressMsg(final ProgressDialog dialog,final String value){
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.setMessage(value);
}
});
}
private void changeStatusImg(final ImageView imgView, final int imgId){
runOnUiThread(new Runnable() {
#Override
public void run() {
imgView.setImageResource(imgId);
}
});
}
Sever.java
public class Server {
public static void main(String[] args) {
new Server().startServer();
}
public void startServer() {
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Waiting for clients to connect...");
while (true) {
Socket clientSocket = serverSocket.accept();
clientProcessingPool.submit(new ClientTask(clientSocket));
}
} catch (IOException e) {
System.err.println("Unable to process client request");
e.printStackTrace();
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
private class ClientTask implements Runnable {
private final Socket clientSocket;
private ClientTask(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
System.out.println("Got a client !");
// Do whatever required to process the client's request
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

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.

Communicating android and windows through socket

I want to make my android app open socket to my windows console app and they communicate with each other. The socket is opened and data is sent and received in windows app, but my android app does not receive the answer which sent by windows. I watch the packets in my android and I saw the packets are coming but I do not know why my app do not receive it!
windows app server class:
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
Console.WriteLine("\nStarting server...");
this.tcpListener = new TcpListener(IPAddress.Any, 1234);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
Console.WriteLine("\nWaiting for clients to connect...");
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
Console.WriteLine("\nIncoming from client...");
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
try
{
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("\nReceived: \n\n" + encoder.GetString(message, 0, bytesRead));
//By FMR
string response = "random responsive: " + new Random().Next(1000).ToString() + "\n";//"\r\n";
//writeData(clientStream, response);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// Send back a response.
clientStream.Write(msg, 0, msg.Length);
clientStream.Flush();
Console.WriteLine("\nResponed ..." + response);
}
}
catch (Exception ex)
{
Console.WriteLine("\nException while: " + ex.Message);
}
tcpClient.Close();
}
}
my android thread:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Socket socket = null;
ServerSocket serverSocket = null;
Boolean bRun = true;
try {
socket = new Socket(ip, port);
if(outputStream == null) {
outputStream = new DataOutputStream(socket.getOutputStream());
}
// become server
serverSocket = new ServerSocket(port);
Log.i(G.TAG, "before serverSocket.accept");
socket = serverSocket.accept();
Log.i(G.TAG, "response recieve: ");
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (Exception e) {
try {
serverSocket.close();
} catch (IOException e1) {
Log.e(G.TAG, "serverSocket.close() e: " + e1.getMessage());
}
try {
socket.close();
} catch (IOException e1) {
Log.e(G.TAG, "socket.close() e: " + e1.getMessage());
}
}
Log.i(G.TAG, "after start recieve: ");
while (bRun) {
try {
Log.i(G.TAG, "while start: ");
String message = inputStream.readLine();
Log.i(G.TAG, "response message: " + message);
if (message != null) {
setListMessage(false, message);
}
}
catch (IOException e) {
bRun = false;
Log.e(G.TAG, "while bRun e: " + e.getMessage());
}
}
}
});
thread.start();
// in another function, my message is sent successfully from android and receive in windows
I found the problem, this line
socket = serverSocket.accept();
made the problem when I comment the line, the android app received the response!
Does anybody know why?

client Windows and Android server over USB

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

Categories

Resources