Android socket principle and exception - java

i'm begginer with java socket in android. i'm have some problem and need help for solving them.
I'm connect to server Socket with bottom code and every thing is fine. but when call disconnect method and try to connect again i faced with problem such socket is null or BufferedReader object always return null after disconnect and connect again. maybe my disconnect way is wrong. what is the best way for disconnect socket at some time like intrupt internet and connect again?
Here is my code for connecting and disconnecting socket.
public class HelperSocket {
public static Socket socket = null;
public static DataOutputStream writer = null;
public static BufferedReader reader = null;
public static DataInputStream inputStream = null;
public static final String SOCKET_ADDRESS = "aUrlForSocket";
public static final int SOCKET_PORT = 6000;
public static final int SOCKET_TIMEOUT = 30000;
public static Thread clientThread;
public static boolean isConnected = false;
public static boolean connect() {
Utils.Log("StartConnect");
if (!isConnected) {
clientThread = new Thread(new Runnable() {
#Override
public void run() {
try {
InetAddress address = InetAddress.getByName(HelperSocket.SOCKET_ADDRESS);
socket = new Socket(address.getHostAddress(), SOCKET_PORT);
isConnected = true;
socket.setSoTimeout(SOCKET_TIMEOUT);
writer = new DataOutputStream(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
inputStream = new DataInputStream(socket.getInputStream());
while (HelperSocket.isConnected) {
Utils.Log("onWhile" + reader.hashCode());
try {
if (reader.readLine() != null) {
Utils.Log(reader.readLine() + "");
} else {
Utils.Log("getNullFromServer");
//data get null here :)
disconnect();
}
} catch (IOException e) {
Utils.Log("ProblemOnReadData" + e.getMessage());
e.printStackTrace();
}
}
} catch (IOException e) {
Utils.Log("SocketProblemAt connect:" + e.getMessage());
e.printStackTrace();
}
}
});
clientThread.start();
}
return true;
}
public static boolean disconnect() {
isConnected = false;
if (!clientThread.isInterrupted())
clientThread.interrupt();
if (socket != null) {
Utils.Log("SocketAndAllObjectCleared");
try {
socket.shutdownInput();
socket.shutdownOutput();
socket = null;
} catch (IOException e) {
e.printStackTrace();
}
/* stream = null;
reader = null;*/
}
return false;
}
}
I create a reciever in network connectivity change, and need to disconnect socket when device not connect to internet and connect again when internet connection established.
The receiver:
public class BroadcastChangeNet extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Utils.isNetworkConnected()) {
HelperSocket.connect();
Utils.Log("NetWorkConnect");
} else {
HelperSocket.disconnect();
Utils.Log("NetWorkDisConnect");
}
}
}
Checking network situation:
public static boolean isNetworkConnected() {
ConnectivityManager conMgr =
(ConnectivityManager) ApplicationClass.context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i == null)
return false;
if (!i.isConnected())
return false;
if (!i.isAvailable())
return false;
return true;
}

From my point of view you simply need to create saprate Jave class, below is my code that i tested successfully,
import android.content.Context;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* Created by Kintan Patel on 01-08-2016.
*/
public class SocketConnection {
private Socket socket = null;
private OutputStream outputStream;
private DataOutputStream dataOutputStream;
private SessionHelper helper;
public String EstablishConnection(String token) {
// token = your message that write on socket server
String response;
try {
//socket = new Socket("192.168.0.24", 2129); // Testing Server
socket = new Socket("Your IpAddress", PORT NO);
outputStream = socket.getOutputStream();
dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeUTF(token);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
response = br.readLine();
} catch (UnknownHostException e) {
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
return null;
} catch (SocketException e) {
e.printStackTrace();
response = "Sorry Fail to connect";
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
response = "Sorry Fail to connect";
return null;
} catch (Exception e) {
e.printStackTrace();
response = "Server Break";
return null;
} finally {
if (socket != null) {
try {
socket.close();
outputStream.close();
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
}
Now from your main class simply create the object of SocketConnection class and use EstablishConnection() method,
eg :
SocketConnection connection = new SocketConnection();
String token = "message that you want to write on server";
String response = connecation.EstablishConnection(token);
if you want to use AsynkTask than below is AsynkTask code :
private class ActivationTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
SocketConnection connection = new SocketConnection();
String token = "getActivation|" + params[0] + "|";
return connection.EstablishConnection(token);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
if (s != null) {
Log.e("RESULT" , s);
}
}
}

Related

How to connect android device with bluetooth as server to 4 client devices and receive send data to server

I want to create two apps in android java, to connect through bluetooth and send and receive data. I already implement both apps. but the problem is when i want to connect more than one client to the server app and send data from all clients to the server. but server only can get data from first client. before i heard one server can connect to five client at the same time.
is it right?
private class Server extends Thread {
private BluetoothServerSocket serverSocket;
public Server() {
try {
serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(APP_NAME, uuid);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
BluetoothSocket bluetoothSocket = null;
while (bluetoothSocket == null) {
try {
bluetoothSocket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
if (bluetoothSocket != null) {
sendReceive = new SendReceive(bluetoothSocket);
sendReceive.start();
break;
}
}
}
}
private class SendReceive extends Thread {
private BluetoothSocket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(BluetoothSocket socket1) {
socket = socket1;
InputStream tempIn = null;
OutputStream tempOut = null;
try {
tempIn = socket.getInputStream();
tempOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
inputStream = tempIn;
outputStream = tempOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true){
try {
bytes = inputStream.read(buffer);
Log.i(TAG, "server receive: " + new String(buffer, 0 , buffer.length).trim());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class Client extends Thread {
BluetoothDevice device;
BluetoothSocket socket;
public Client(BluetoothDevice device1) {
device = device1;
try {
socket = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
socket.connect();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
Log.i("blt", "run Client " + e.getMessage());
}
}
}
private class SendReceive extends Thread {
private BluetoothSocket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(BluetoothSocket socket1) {
socket = socket1;
InputStream tempIn = null;
OutputStream tempOut = null;
try {
tempIn = socket.getInputStream();
tempOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
Log.i("blt", "SendReceive " + e.getMessage());
}
inputStream = tempIn;
outputStream = tempOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes) {
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
what should i change in my code to be able to connect more than one client to the server and receive data from all clients?

Android Sockets not working in reality

I am trying to connect an Android device to a java server. It works perfectly when I use the emulator but when I port it onto my phone there is no connection.
The aim of the code is to send a value from client to server, perform a calculation on it and return it back to the client to be displayed.
This is my server code:
public class ServerTest {
public static final int PORT_NUMBER = 8000;
protected Socket socket;
private ServerTest(Socket socket) {
this.socket = socket;
System.out.println("New client connected from " + socket.getInetAddress().getHostAddress());
connect();
}
public void connect() {
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String request = br.readLine();
if (request.equals("end")) {
System.out.println("Message received: " + request + ". Ending connection.");
request = "End Connection";
out.write(request.getBytes());
in.close();
out.close();
socket.close();
System.exit(0);
} else {
System.out.println("Message received: " + request);
request = calculatePi(request);
System.out.println("Output: " + request);
out.write(request.getBytes());
}
} catch (IOException ex) {
System.out.println("Unable to get streams from client");
} finally {
try {
in.close();
out.close();
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("Welcome. IP address is: " + getIP());
ServerSocket server = null;
try {
server = new ServerSocket(PORT_NUMBER);
while (true) {
new ServerTest(server.accept());
}
} catch (IOException ex) {
System.out.println("Unable to start server.");
} finally {
try {
if (server != null)
server.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static String getIP() {
String ip = "";
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
// *EDIT*
if (addr instanceof Inet6Address) continue;
ip = addr.getHostAddress();
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
return ip;
}
and this is my client side code on device:
public class MainActivity extends AppCompatActivity {
TextView piResultTextView;
EditText addressEditText, messageEditText;
Button connectButton;
Handler handler = new Handler();
Results results;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
results = new Results();
addressEditText = findViewById(R.id.AddressEditText);
messageEditText = findViewById(R.id.MessageEditText);
connectButton = findViewById(R.id.ConnectButton);
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connect();
}
});
piResultTextView = findViewById(R.id.PiResultTextView);
}
public void connect() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
String hostAddress = addressEditText.getText().toString();
int port = 8000;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(hostAddress, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
Toast.makeText(getApplicationContext(), "Unknown host: " + hostAddress, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to get streams from server", Toast.LENGTH_SHORT).show();
}
String input = messageEditText.getText().toString();
try {
out.println(input);
results.pi = in.readLine();
handler.post(new Runnable() {
#Override
public void run() {
piResultTextView.setText(results.pi);
}
});
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to read input stream from server", Toast.LENGTH_SHORT).show();
}
try {
out.close();
in.close();
echoSocket.close();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error closing streams", Toast.LENGTH_SHORT).show();
}
}
});
thread.start();
}
}

Android tcp client app crash by connection

I develope a simple chat app with login and register.
For the communication I use TCP Client and a TCP Server.
If user click to login I connect to the server.
Now I need to check if connected or not. If returns true I start a new intent.
I don't have rooted android phone to see the logs and my computer is to low for the emulator, but maybe the fail can you see in the source.
If the progress dialog done loaded is the app crash. Maybe I need a Exception..
Login:
public void LoginUser() {
class AttemptLogin extends AsyncTask<String, Void, Boolean> {
ProgressDialog pDialog;
private Context context;
public AttemptLogin(Activity activity) {
context = activity;
pDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage(context.getString(R.string.login) + "...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(String... args) {
session = new Session(getBaseContext(), "Azcaq", "Azcaq $$", "Test");
session.client = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
public void messageReceived(String message) {
}
});
session.client.run();
Login();
return null;
}
protected void onPostExecute(final Boolean success) {
pDialog.dismiss();
}
}
new AttemptLogin(this).execute();
}
public void Login() {
if(session.client.isConnected()) {
session.setLogin(true);
Intent intent = new Intent(this, ChatsActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), getString(R.string.connectionfail), Toast.LENGTH_LONG).show();
}
}
TcpClient
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
public class TcpClient {
public static final String SERVER_IP = "82.168.0.198";
public static final int SERVER_PORT = 64000;
private String mServerMessage;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
private PrintWriter mBufferOut;
private BufferedReader mBufferIn;
private Boolean connected = false;
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
public void sendMessage(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
public Boolean isConnected() {
if(connected) {
return true;
}
return false;
}
public void stopClient() {
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
connected = false;
}
public void run() {
mRun = true;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Socket socket = new Socket(serverAddr, SERVER_PORT);
try {
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(socket.isConnected()) {
connected = true;
}
while (mRun) {
try {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
mMessageListener.messageReceived(mServerMessage);
}
} catch (SocketTimeoutException e) {
} catch (IOException e) {
}
}
} catch (SocketException e) {
} catch (Exception e) { } finally {
socket.close();
}
} catch (Exception e) {
}
}
public interface OnMessageReceived {
public void messageReceived(String message);
}
}

Outputting Every Other Time

I have made an application that opens up a socket via a thread and updates based on what is typed. Here is the code:
Server.java:
public class Server {
public static void main(String[] args) throws IOException {
int portNumber = 2392;
boolean listening = true;
System.out.println("Server: Running...");
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
System.out.println("Server: Connected to Client!");
while (listening) {
new ServerThread(serverSocket.accept()).start();
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection( '" + e.getMessage() + "' );");
} finally {
System.out.println("Server: Disconnecting...");
}
}
}
Server Thread.java:
public class ServerThread extends Thread {
private Socket socket = null;
Scanner reader = new Scanner(System.in);
public ServerThread(Socket socket) {
super("ServerThread");
this.socket = socket;
}
public void run() {
System.out.println("Ruasd");
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
String outputLine = "";
while (!outputLine.equals("Disconnect")) {
outputLine = reader.nextLine();
out.println(outputLine);
}
socket.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client.java:
public class MainActivity extends Activity {
private Socket socket;
private TextView status;
private BufferedReader in;
private Handler mHandler;
private static final int SERVERPORT = 2392;
private static final String SERVER_IP = "...ip#...";
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_vitals);
status = (TextView) findViewById(R.id.text_status);
new Thread(new CommunicationThread()).start();
}
#Override
protected void onStop() {
super.onStop();
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class CommunicationThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
final String fromServer = in.readLine();
System.out.println("Server: " + fromServer);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
status.setText(fromServer);
}
});
if (fromServer.equals("Disconnect."))
break;
}
} catch (IOException e) {
e.printStackTrace();
}
It works perfectly the first time and outputs to the status TextView correctly. However, when I restart the application, it outputs every other word. For instance, If I type "Hey" "Hi "You" "How", I will see "Hi" and "How" in the TextView the second time I start the application.
What's really odd to me is that when I do System.out.println("Server: " + fromServer) it is outputting all values. Any suggestions are greatly appreciated.
Ok I think I found the problem (got it working for me, that is). In your CommunicationThread, you didn't have a while loop. Also, you need to iterate the server's input until it is null. See below:
class CommunicationThread implements Runnable {
#Override
public void run() {
try {
// keep the connection alive.
while (true) {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String fromServer;
// get server messages until there are none
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
status.setText(fromServer);
}
});
if (fromServer.equals("Disconnect."))
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please get back to me on how it works out :)

Socket from Server (java app) to Android app

I have a problem, and I don´t know if it´s possible.
I have an Android app that are a client socket.
This is the code to send a message to a server in Android App:
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
System.out.println("envia mensaje");
client = new Socket("ip of server", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
At same time, in Android App, a socket is created in 4445 port:
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 4445;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println(message);
}
});
/*SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();*/
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And this is the server code, that create a socket in 4444 port:
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println("Dirección entrante"+clientSocket.getInetAddress());
//System.out.println("Dirección entrante2"+clientSocket.get());
System.out.println(message);
ip_a = clientSocket.getInetAddress().toString().substring(clientSocket.getInetAddress().toString().indexOf("/")+1, clientSocket.getInetAddress().toString().length());
//message.substring(message.indexOf(":")+1, message.length()).trim();
System.out.println("realiza conexión a ip:#"+ip_a+"#");
messsage = "enviado desde el servidor"; // get the text message on the text field
SendMessage(ip_a);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
This work correctly, but I want send a message from server to a Android device throug IP that socket have.
I try with clientSocket.getInetAddress(), and with clientSocket.getRemoteSocketAddress(), but not work. I create a socket in Android app in 4445 port, but the server can´t connect to socket of android app.
Can you help me?
Thanks in advance
Ok, I will try.
This is my server aplication:
import java.io.BufferedReader;
import java.io.IOException;
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.net.UnknownHostException;
import java.util.Enumeration;
public class SimpleTextServer {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static Socket client;
private static String messsage;
private static PrintWriter printwriter;
static String ip_a;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
System.out.println("Server started. Listening to the port 4444:"+getIpAddress());
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println("Dirección entrante"+clientSocket.getInetAddress());
//System.out.println("Dirección entrante2"+clientSocket.get());
System.out.println(message);
ip_a = clientSocket.getInetAddress().toString().substring(clientSocket.getInetAddress().toString().indexOf("/")+1, clientSocket.getInetAddress().toString().length());
//message.substring(message.indexOf(":")+1, message.length()).trim();
System.out.println("realiza conexión a ip:#"+ip_a+"#");
messsage = "enviado desde el servidor"; // get the text message on the text field
SendMessage(ip_a);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
public static void SendMessage(String ip) {
try {
System.out.println("comienza a enviar mensaje");
client = new Socket(ip, 4445); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static 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 += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
And this is my activity in my Android app:
package com.lakj.comspace.simpletextclient;
import java.io.BufferedReader;
import java.io.IOException;
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.net.UnknownHostException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SlimpleTextClientActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
//ServerSocket serverSocket;
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slimple_text_client);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
System.out.println("IP DE CLIENTE EMULADOR: "+getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
//myClientTask.execute();
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("ENVIA MENSAJE BOTON");
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
System.out.println("envia mensaje");
client = new Socket("ip de servidor", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.slimple_text_client, menu);
return true;
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 4445;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println(message);
}
});
/*SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();*/
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
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 += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
If I run the android app, the message is sended to server, and server show it.
But, the server can´t connect to Android. The IP is unracheable. I don´t know why...

Categories