Unable to read input from a bluetoothsocket - android

I've finally managed to connect from my android phone to my device, put I have a problem when I try to read from my bluetooth socket.
So here is my code for establishing connecting to my device, its a class that extends AsyncTask
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
public class Connect extends AsyncTask<String, Void, String> {
private final static String TAG = "+++CONNECT THREAD+++";
ProgressDialog progressDialog;
Context context;
BluetoothSocket tmp;
BluetoothDevice device;
BluetoothAdapter ba;
Button connect;
int bt_port_to_connect;
ReadInput ri;
InputStream is;
byte[] test;
public Connect(Context context, BluetoothDevice device, BluetoothAdapter ba, Button connect) {
this.ba = ba;
this.context = context;
this.device = device;
this.connect = connect;
bt_port_to_connect = 9;
}
protected void onPreExecute() {
progressDialog=ProgressDialog.show(context,"Please Wait..","Connecting to device",false);
}
#Override
protected String doInBackground(String... arg0) {
Method m = null;
try {
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, bt_port_to_connect);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ba.cancelDiscovery();
tmp.connect();
ri = new ReadInput(tmp);
ri.start();
} catch (IOException e) {
Log.e("+++CONNECT1+++","EXCEPTION: " + e.getMessage());
try {
tmp.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + " insecure socket type" +
" socket during connection failure", e2);
}
Log.e("+++CONNECT2+++", e.getLocalizedMessage());
}
boolean isConnected = tmp.isConnected();
if(isConnected) {
return "connected";
}
else {
return "notConnected";
}
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
if(result.equals("connected")) {
connect.setEnabled(false);
Toast.makeText(context, "Connected to device: "+device.getName().toString(), Toast.LENGTH_LONG).show();
//new ReadIn(context, tmp).execute("");
}
else if(result.equals("notConnected")) {
Toast.makeText(context, "Can`t reach host", Toast.LENGTH_LONG).show();
}
}
}
As you can see, the line below tmp.connect(); I create a new object of a new class, this is the class which I want to handle the reading of the inputStream So here is the code for that class:
import java.io.IOException;
import java.io.InputStream;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ReadInput extends Thread {
BluetoothSocket socket;
private InputStream is;
public ReadInput(BluetoothSocket socket) {
Log.i("READINPUT", "INSIDE READ INPUT THREAD CONSTRUCTOR!!!");
InputStream tmpIn = null;
this.socket = socket;
is = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e("READINPUT", "Temp socket in created: " + e.getMessage());
}
is = tmpIn;
}
public void run() {
Log.i("READINPUT", "INSIDE READ INPUT THREAD RUN METHOD!!!");
byte[] buffer = new byte[1024];
int bytes = 0;
while(true) {
try {
bytes = is.read(buffer);
} catch (IOException e) {
Log.e("FROM RUN METHOD: ", e.getMessage());
}
Log.i("INPUTSTREAM GOT: ", Integer.toString(bytes));
}
}
}
I have two Log.i methods in my last code, this outputs the correct info to LogCat stating where in the code I am. But it doesnt output the content of the stream to LogCat. What am I doing wrong here? Yes, I've looked into the BluetoothChat example.
Thanks in advance!
EDIT 1
I've done some research in the constructor of the ReadInput Class.
is = tmpIn;
try {
Log.i("InputStream: ", Integer.toString(is.available()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This snippet will only output to logcat that is returns 0 which means that the InputStream is not available. Any suggestions?

I found using a buffered reader works well with a blietooth device. And then I just used a while.loop with br.isReady in a while true listener. Basically makes a "listener"

Related

Android InputStream reads garbage ServerSocket running in a Thread. How should ServerSocket read from client socket?

I have a an application which communicates between two android devices through socket. It seems like they do connect, but when data from the client socket is read by ServerSocket (using InputStream), it doesnot return the desired result (it is supposed to return somrthing like "21.24891706//95.23659845//ff8iuj67898n47fu" ).Instead I'm getting " [B#416b9488" as the message.
My client runs an AsyncTask and server runs a Thread.
Can you please help me solve this problem? Any help will is appreciated. Thanks in advance.
Here is Server.java which runs on the server:
import android.content.Context;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
public class Server {
Context context;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
ShowConnectedStudents activity;
public Server(ShowConnectedStudents callingActivity) {
activity = callingActivity;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
byte buffer[] = new byte[1024];
int bytesRead;
String message;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket=new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(socketServerPORT));
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
message = "";
InputStream input = socket.getInputStream();
BufferedInputStream br= new BufferedInputStream(input);
while ((bytesRead = br.read(buffer)) != -1 ) {
message += " " + buffer.toString();
}
message += socket.isConnected();
message+=":"+socket.isClosed();
input.close();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.status.setText("Message is: " + message);
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Here is Client.java which runs on the client:
import android.os.AsyncTask;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String status = "";
double Lat,Long;
String deviceId;
Socket socket = null;
ConnectToDevice activity;
byte buffer[] = new byte[1024];
int bytesRead;
Client(String addr, int port,double latitude,double longitude,String deviceIdentification,ConnectToDevice callingActivity) {
dstAddress = addr;
dstPort = port;
Lat=latitude;
Long=longitude;
deviceId=deviceIdentification;
activity=callingActivity;
if(dstAddress.charAt(0)=='/'){
dstAddress=dstAddress.substring(1);
}
}
#Override
protected Void doInBackground(Void... arg0) {
while(socket==null){
try {
socket = new Socket(dstAddress, dstPort);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream outputStream = socket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream,true);
printStream.print(Lat + "//" + Long+"//"+deviceId);
printStream.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
status = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
status = "IOException: " + e.toString();
} finally {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
activity.statusText.setText(Lat+ "//" + Long+"//"+deviceId);
super.onPostExecute(result);
}
}
toString() on a byte[] is not what you want, you're getting basically the memory address of the byte array
instead convert to a string, something like this
while ((bytesRead = br.read(buffer)) != -1 ) {
message += " " + new String(buffer, 0, bytesRead);
}
I have figured out another way, before reading this accepted answer. I'm posting it in case if it benefit anyone.
My data is text-only. So I wrapped the socket's input stream inside a Scanner.
InputStream input = socket.getInputStream();
Scanner scanner= new Scanner(input);
while(scanner.hasNextLine()){
message+=scanner.nextLine();
}

Unable to read data (send by server) at Client Side

I am trying to develop an app in which
1.client sends request to server for connection(IP address+PORT no.)+sends data using "PrintStream"+Tries to read the data from Server(Using Inputstream)
2.Client creates the socket.
3.Server reads the data send by Client
4.SERVER writes the data using "PrintStream" at same time point no 3.
Problem is at point 4 Data written by SERVER is not Read by "INPUTSTREAM" of client(Point 1)
I dont know these Simultaneous operation are possible or not.If possible then how.If not then what is the alternate way?
Server Code
package com.example.loneranger.ser;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends Activity {
TextView ip;
TextView msg;
String data = "";
ServerSocket httpServerSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
ip.setText(getIpAddress() + ":"
+ 8080 + "\n");
Server server = new Server();
server.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (httpServerSocket != null) {
try {
httpServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private 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 += "IP: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
private class Server extends Thread {
#Override
public void run() {
Socket socket = null;
try {
httpServerSocket = new ServerSocket(8888);
while(true){
socket = httpServerSocket.accept();
HttpResponseThread httpResponseThread =
new HttpResponseThread(
socket);
httpResponseThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class HttpResponseThread extends Thread {
Socket socket;
HttpResponseThread(Socket socket){
this.socket = socket;
}
#Override
public void run() {
BufferedReader BReader;
PrintWriter printer;
String request;
try { InputStream inputStream = socket.getInputStream();
BReader = new BufferedReader(new InputStreamReader(inputStream));
request = BReader.readLine();
Thread.sleep(500);
printer = new PrintWriter(socket.getOutputStream(), true);
printer.print("hello laundu");
printer.flush();
String ip123=socket.getInetAddress().toString();
printer.close();
BReader.close();
socket.close();
data += "Request of " + request
+ " from "+ ip123 + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(data);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
}
}
Client Code
mport android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
MainActivity activity;
OutputStream outputStream;
BufferedReader BReader;
String request;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse=textResponse;
this.activity=activity;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
Server server = new Server(socket);
server.start();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.print("futfujb");
out.flush();
/*
* notice: inputStream.read() will block if no data return
*/
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} /*finally {
if (socket != null) {
try {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
private class Server extends Thread {
Socket socket;
Server(Socket socket)
{
this.socket=socket;
}
#Override
public void run() {
try { //Thread.sleep(500);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
if(inputStream.available()>0)
{
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
inputStream.close();
socket.close();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
As I commented above, there is nothing in this code that corresponds to either of these steps:
2.Server gets the request creates new SOCKET connection.
(a) There is no request, and (b) the server does not create a new connection. The client creates it. The server accepts it.
3.Server reads the data send by Client.
The client doesn't send any data.
There are two problems here (at least):
The server is blocking in readLine() waiting for a message that the client never sends. So it never gets to its own send, so nothing is received by the client. Have the client send a request, as per the comments.
The client is incorrectly using available(). Remove this test and let the client fall through into the read loop. It will exit that when the peer (the server) closes the connection.

Android Sockets between devices

I've trying to connect 2 devices by sockets, but it never works. One of the devices is the Server that save the configuration (IP and port where listen) on a database, then the other device,the Client , connect with the database and take the configuration to conect.
Database querys and echos works fine (PHP) but the method wich open the client socket doesn't work, it run out of time to connect and throws an exception. I dont know if the ServerSocket doesn't receive the petition or the ClientSocket doesn't send it...
The code below: (bit bad, but is for test).
Server code:
public class Server{
private int puerto = 4567;
private ServerSocket serverSocket;
public void conectar() {
try {
serverSocket = new ServerSocket(puerto);
while (true) {
Log.i("SocketServer", "escuchando");
Socket cliente = serverSocket.accept();
Log.i("Socket","Cliente ha conectado");
BufferedReader ent = new BufferedReader(new InputStreamReader(
cliente.getInputStream()));
String linea = ent.readLine();
Log.i("Cliente", "Cliente envia=" + linea);
cliente.close();
Log.i("Servidor","Cliente desconectado");
}
} catch (IOException e) {
Log.e("Error", "Error en el servidor");
}
}
Client code:
public class Cliente {
private int puerto;
private InetAddress direccion;
public Cliente(int puerto, InetAddress direccion){
this.puerto = puerto;
this.direccion = direccion;
}
public void conectar(){
try{
Socket cliente = new Socket(direccion, puerto);
Log.i("Cliente", "Conectado");
conectado = true;
PrintWriter salida=new PrintWriter(cliente.getOutputStream(),true);
salida.println("Hola, soy el cliente");
Log.i("Cliente", "Mensaje enviado");
cliente.close();
}catch(SocketException e){
Log.e("ErrorSocket","Error al abrir socket " + e.getMessage());
} catch (IOException e) {
Log.e("ErrorSocket","Error al enviar " + e.getMessage());
}
}
}
I get the InetAddress by method below:
//The String result param is like: "192.168.0.1&23456"
public InetAddress getInetAddress(String result) {
InetAddress address = null;
//5 it an example
if (result.length() > 5 && result != null) {
try {
String[] data = result.split("&");
Log.i("Data", data[0] + " " + data[1]);
puerto = Integer.parseInt(data[1]);
Log.i("PUERTO", "Puerto:" + puerto);
String ip = data[0];
Log.i("IP", ip);
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]);
}
address = InetAddress.getByAddress(IP);
Log.i("InetAddress",address.getCanonicalHostName());
} catch (Exception e) {
Log.e("Error", "Error al conseguir InnetAddress");
}
} else {
Log.e("Error", "String capturado vacio");
return address;
}
return address;
}
Thanks :)
It a test project for my College Final Project, a GPS-Chat.
EDIT: 3G nat breaks this way to develop an android connection between 2 devices by sockets. I'll study the way to do it with GCM and another server.
For your client code I find that this works really well for me:
OutputStreamWriter wr = new OutputStreamWriter(cliente.getOutputStream());
Then to send data use:
wr.write("DATA TO SEND");
wr.flush();
It looks like you have good logging going on, I would also add Log output lines to see if it got past the socket and have it print out all of the data that you get. If all of the logs show the correct data but the client just won't connect, try the code I posted above, I haven't had problems with it.
ServerApplication.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
public class ServerApp {
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable{
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket){
try {
sock=clientSocket;
InputStreamReader isr=new InputStreamReader(sock.getInputStream());
reader=new BufferedReader(isr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
String message;
try {
while((message=reader.readLine())!=null)
{
System.out.println("read :"+message);
tellEveryone(message);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void tellEveryone(String message) {
// TODO Auto-generated method stub
Iterator itr=clientOutputStreams.iterator();
while(itr.hasNext()){
PrintWriter pWriter=(PrintWriter)itr.next();
pWriter.println(message);
pWriter.flush();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ServerApp().createSocket();
}
private void createSocket() {
// TODO Auto-generated method stub
clientOutputStreams=new ArrayList();
try {
ServerSocket socket=new ServerSocket(5000);
while(true){
Socket clientSocket=socket.accept();
PrintWriter writer=new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("Got a Connection to the Client");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Chat Client Source Code
===================================================
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
public class ChatClient {
JTextField outgoing;
JTextArea incoming;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public void layOutDesign(){
JFrame frame= new JFrame("Simple Chat Client");
JPanel mainPanel= new JPanel();
incoming= new JTextArea(15,25);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller=new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing=new JTextField(20);
JButton sendButton=new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setupNetworking();
Thread readerThread=new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(400, 500);
frame.setVisible(true);
}
private void setupNetworking() {
// TODO Auto-generated method stub
try {
sock=new Socket("10.30.10.156", 5000);
InputStreamReader isR=new InputStreamReader(sock.getInputStream());
reader=new BufferedReader(isR);
writer=new PrintWriter(sock.getOutputStream());
System.out.println("Network Established.");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class SendButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent ev) {
// TODO Auto-generated method stub
try{
writer.println(outgoing.getText());
writer.flush();
}catch (Exception e1) {
// TODO: handle exception
e1.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ChatClient().layOutDesign();
}
public class IncomingReader implements Runnable{
String message;
#Override
public void run() {
// TODO Auto-generated method stub
try {
while((message=reader.readLine())!=null){
System.out.println("Read :"+message);
incoming.append(message+"\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Go to server code...
and change the IP of your System
then connect to the Clients
And enjoy the Chatting between your colleagues in your Network....
Better option for exchange information about GPS position is use websocket. I very simple server for this kind of application https://github.com/yoman07/geo_server demo class for android you can find here https://github.com/yoman07/PhotoShoter/blob/master/PhotoShoterModule/src/main/java/com/photoshoter/SocketClient.java .

A simple client-server - Android<>PC

I am testing socket programming on Android however I am having a problem. The client is basically launched through the main activity with a basic function of sending a message to the server and getting a reply.
the client activity:
package com.test.socket;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class socketActivity extends Activity implements OnClickListener {
String input;
private EditText et;
private ObjectOutputStream oos;
private TextView tv;
private String message;
private ObjectInputStream ois;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket(host.getHostName(),7777);
//send to server
oos = new ObjectOutputStream(socket.getOutputStream());
et = (EditText) findViewById(R.id.text);
Button sendButton = (Button) findViewById(R.id.button);
sendButton.setOnClickListener(this);
//read from server
ois = new ObjectInputStream(socket.getInputStream());
//System.out.println("Message from Server: "+message);
tv = (TextView) findViewById(R.id.textView);
}
catch(UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button:
input = et.getText().toString();
try {
oos.writeObject(input);
ois.close();
oos.close();
message = (String) ois.readObject();
tv.setText("Message from Server: "+message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
The Server class launched separately from JCreator listening to port 7777:
import java.io.*;
import java.lang.*;
import java.net.*;
public class server {
private ServerSocket server;
private int port = 7777;
public server()
{
try{
server = new ServerSocket(port);
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
server example = new server();
example.handleConnection();
}
public void handleConnection()
{
System.out.println("Waiting for client message...");
while(true)
{
try{
Socket socket = server.accept();
new ConnectionHandler(socket);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
ConnectionHandler class which the Server accesses:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ConnectionHandler implements Runnable {
private Socket socket;
public ConnectionHandler(Socket socket)
{
this.socket = socket;
Thread t = new Thread(this);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
try{
//receive from client
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message from client: "+message);
if(message.equals("check"))
{
System.out.println("Checking for malicious interference...");
Thread.sleep(5000);
System.out.println("Status: Files are good.");
}
//send response to client
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
if(message.equals("check"))
{
oos.writeObject("Checking...");
}
else oos.writeObject("Invalid input");
ois.close();
oos.close();
socket.close();
System.out.println("Waiting for client message...");
}
catch(IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have tested the code on JCreator and Eclipse through Java application not Android app and it worked perfect. However when I try doing it through the activity, it's not working.
Any ideas?
In Android, localhost would point to the phone/emulator itself. It doesn't point to your server. The following line below is pointing to your Android device/emulator and not your server. You need to get the actual IP of the server to get it working from your Android
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket(host.getHostName(),7777);
It works through Java App, because when you execute it from the context of Java Application, the localhost is pointing to the same server location.

Problem opening a Socket

I'm building a very small app to send data from the cellphone to a computer. I've read a couple of examples and got the server and client code working. But when i try to connect them, got a "network unreachable" error. Any idea what am i doing wrong??
This is the Server Code:
import java.net.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Server {
static BufferedReader in = null;
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("FrameDemo");
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
try {
if (in != null)
in.close();
if (serverSocket.isClosed())
{}
else
serverSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JLabel Label = new JLabel("");
Label.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(Label, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
Label.setText("Empezo");
serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.err.println(e.getMessage());
System.exit(1);
}
Integer puerto = serverSocket.getLocalPort();
Label.setText("<html>Puerto Abierto: " + puerto.toString() + "<br>IP Servidor: " + serverSocket.getInetAddress().toString() + "</html>");
clientSocket = null;
try {
clientSocket = serverSocket.accept();
Label.setText("Conection Accepted");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
while ((in.readLine()) != null) {
System.out.println("Mensaje: " + in.readLine());
}
}
}
And the Cliente part
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class PruebaSocket extends Activity {
/** Called when the activity is first created. */
Socket Skt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Enviar =(Button)findViewById(R.id.OK);
Button Salir = (Button)findViewById(R.id.SALIR);
final TextView IP = (TextView)findViewById(R.id.IP);
Skt = new Socket();
Enviar.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
try{
Skt = new Socket("192.168.1.101",4444);
CharSequence errorMessage = "Coneccted";
Toast.makeText(PruebaSocket.this, errorMessage, Toast.LENGTH_SHORT).show();
}
catch(Exception E)
{
CharSequence errorMessage = E.getMessage();
Toast.makeText(PruebaSocket.this, errorMessage, Toast.LENGTH_SHORT).show();
if (Skt.isConnected())
try {
Skt.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Salir.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
try {
Skt.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
}
}
192.168.1.101 it's the IP of the server.
I don't know much about java sockets but the normal usage of a socket is: create, bind, and put in listen mode (udp) or call .accept() (tcp). I can see Java also has the binding phase - http://download.oracle.com/javase/1.5.0/docs/api/java/net/ServerSocket.html#bind(java.net.SocketAddress, int).

Categories

Resources