I am developing andorid aplication for connection to ELM327 for car unit trought Wifi (my adapter: http://www.obdinnovations.com/mini-vgate-elm327-wifi-obd2-auto-diagnostics-scanner).
How should I connect to this OBD2 adapter and then send some signals?
OutputStream outStream = null;
InputStream inStream = null;
Socket socket = null;
InetAddress serverAddr = null;
String serverProtocol = "http";
String serverIpAddress = "192.168.0.10";
public static final int SERVERPORT = 35000;
try {
serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, SERVERPORT);
socket.setKeepAlive(true);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sendDataToOBD(socket1, "ATZ\r");
Log.e("OBD: ATZ", readDataFromOBD(socket));
public void sendDataToOBD(Socket socket1, String paramString) {
try {
outStream = socket1.getOutputStream();
byte[] arrayOfBytes = paramString.getBytes();
outStream.write(arrayOfBytes);
} catch (Exception localIOException1) {
localIOException1.printStackTrace();
}
}
public String readDataFromOBD(Socket socket1) {
while (true) {
try {
inStream = socket1.getInputStream();
String str1 = "";
char c = (char) inStream.read();
str1 = str1 + c;
if (c == '>') {
String datafromOBD = str1.substring(0, -2 + str1.length()).replaceAll(" ", "").trim();
return datafromOBD;
}
} catch (IOException localIOException) {
return localIOException.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I try also with:
URL url = null;
try {
url = new URL(serverProtocol, serverIpAddress, SERVERPORT, "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
And methods param was HttpURLConnection connection instead of Socket socket1.
But I can't receive any signal. What's wrong with my code? Any suggestions?
Related
I'm not getting any errors but I can't send any action to the printer. My ip address and port are correct
I'm trying for the first time. I would be very happy if you could support a little explaining.
public class yazdır extends AsyncTask<Void , Void,Void> {
#Override
protected Void doInBackground(Void... arg0) {
DataOutputStream outToServer ;
Socket clientSocket;
try {
FileInputStream fileInputStream = new FileInputStream(getExternalFilesDir("MyFileDir"+File.separator+"myFile1.txt"));
InputStream is =fileInputStream;
clientSocket = new Socket("ip adress", 9100);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
byte[] buffer = new byte[3000];
while (is.read(buffer) !=-1){
outToServer.write(buffer);
}
outToServer.flush();
return null;
}catch (ConnectException connectException){
Log.e(TAG, connectException.toString(), connectException);
return null;
}
catch (UnknownHostException e1) {
Log.e(TAG, e1.toString(), e1);
return null;
} catch (IOException e1) {
Log.e(TAG, e1.toString(), e1);
return null;
}finally {
}
}
}
Code :
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://192.168.1.8/android-im/index.php"; //TODO change to your WebAPI Address
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = "failed";
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false)
{
//appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
}
my android application needs to communicate with a server python but at the time to receive a response, the answer does not come. These are my codes:
This is my Client:
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 5589;
private static final String SERVER_IP = "192.168.1.131";
TextView risp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
risp = (TextView) findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
out.flush();
// Read from sock
BufferedReader input = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = input.readLine()) != null) {
response.append(line);
}
risp.setText(risp.getText().toString() + " " + response.toString());
out.close();
input.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
And this is the Server:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('192.168.1.131', 5589)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data
while True:
data = connection.recv(1024)
if data.lower() != 'q':
print "<-- client: ", data
else:
print "Quit from Client"
connection.close()
break
data = raw_input("--> server: ")
if data.lower() != 'q':
connection.sendall(data)
else:
print "Quit from Server"
connection.close()
break
finally:
# Clean up the connection
print "Connection close"
connection.close()
The server receive the client message, but the client doesn't receive the server message. Why?
Thanks all in advance
EDIT: I SOLVED it this way:
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 5589;
private static final String SERVER_IP = "192.168.1.131";
TextView risp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
risp = (TextView) findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
new ConnectionTask().execute();
}
class ConnectionTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
String responce = null;
try {
EditText et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
out.flush();
InputStream input = socket.getInputStream();
int lockSeconds = 10*1000;
long lockThreadCheckpoint = System.currentTimeMillis();
int availableBytes = input.available();
while(availableBytes <=0 && (System.currentTimeMillis() < lockThreadCheckpoint + lockSeconds)){
try{Thread.sleep(10);}catch(InterruptedException ie){ie.printStackTrace();}
availableBytes = input.available();
}
byte[] buffer = new byte[availableBytes];
input.read(buffer, 0, availableBytes);
responce = new String(buffer);
out.close();
input.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return responce;
}
protected void onPostExecute(String responce) {
risp.setText(responce);
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I am trying to implement a simple socket that sends and receives strings from a server.
The following code is freezing the application, not sure if I have done something obviously wrong?
public String internetRoutesRetrieve(String userName) {
String command = null;
String response = null;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("Hidden IP", HiddenPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
command = "SEARCH <" + userName + ">";
dataOutputStream.writeUTF(command);
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
Thanks
Edit: It seems the program is freezing when I am trying to save the response from the server
see AsyncTask for proper client server communication on Android application.
you'd usualy get android.os.NetworkOnMainThreadException if you don't but I'd give it a try.
I am working on an android project. Where I am using Socket programming.
But I am getting
java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused.
from emulator.
I have changed the localhost to
"10.0.2.2" ("http://10.0.2.2/abc.php").
I have also followed the java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused.
But I did not get any solution.
Also please note emulator ip address doesn't match with localhost ip address.So I don't know how to get around this.
Here is the code requested for:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import android.util.Log;
import com.mekya.interfaces.IAppManager;
import com.mekya.interfaces.ISocketOperator;
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://billbahadur.com/demo/androidchat/android_im/";
private int listeningPort = 5550;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false)
{
appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public boolean sendMessage(String message, String ip, int port)
{
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
} catch (UnknownHostException e) {
return false;
//e.printStackTrace();
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
}
change android_im to android-im because that is what your folder name would be kept in the web server directory of your server. Also mention the port number of the server in the authentication address.