Socket from Server (java app) to Android app - java

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...

Related

Android Studio tcp client connect to c# server

i started with android a short time ago. This time i tried to connect a c# tcp server with a java tcp client. To debug i worte a c# client and server and if i use the c# client to talk to the server, there is no problem. But my java socket has problems with connecting. I copied the java tcp code for example from the net.
c# code:
namespace MTCliserv2
{
class MTCliserv2
{
static void Main(string[] args)
{
string txt;
Console.Write("MTCliserv2 Server or Client (s/c): ");
txt = Console.ReadLine();
if (txt == "s")
Server();
else
Client();
Console.Write("\nHit any Key to continue "); Console.ReadKey();
}
static IPAddress GetIPAddress()
{
IPAddress ipAdr = Dns.Resolve("localhost").AddressList[0];
ipAdr = IPAddress.Parse("192.168.1.1");
return ipAdr;
}
static void Server()
{
TcpListener server;
Socket socke;
IPAddress ipAdr = GetIPAddress();
try
{
server = new TcpListener(ipAdr, 13);
server.Start();
Console.WriteLine("Server {0} gestartet", server.LocalEndpoint);
while (true)
{
socke = server.AcceptSocket(); // Aufruf blockiert!!
mit diesem Client abwickelt
new ConnTalk(socke);
}
}
catch (Exception e)
{
Console.WriteLine("Error {0}", e);
}
}
static void PrintConnectionInfo(Socket aSock)
{
Console.WriteLine("Anfrage von {0}", aSock.RemoteEndPoint);
}
static void Client()
{
const string serverName = "localhost";
try
{
TcpClient client = new TcpClient("192.168.1.1", 13);
NetworkStream strm = client.GetStream();
Socket sc = client.Client;
StreamReader strmRd = new StreamReader(strm);
StreamWriter strmWr = new StreamWriter(strm);
string txt, txt2;
Console.WriteLine("Connected to {0}", sc.RemoteEndPoint);
while (true)
{
Console.Write("Msg= ");
txt = Console.ReadLine();
if (txt == "end")
break;
strmWr.WriteLine(txt); strmWr.Flush();
txt2 = strmRd.ReadLine();
Console.WriteLine("Answer: {0}", txt2);
}
client.Close(); strmRd.Close(); strmWr.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
// Pro Verbindung wird 1 ConnTalk-objekt erzeugt
class ConnTalk
{
Thread m_Thr;
Socket m_Sc;
public ConnTalk(Socket aSc)
{
m_Sc = aSc;
m_Thr = new Thread(this.TalkWithClient);
m_Thr.Start();
}
void TalkWithClient()
{
NetworkStream strm = new NetworkStream(m_Sc);
StreamReader strmRd = new StreamReader(strm);
StreamWriter strmWr = new StreamWriter(strm);
string txt;
Console.WriteLine("Talking with {0}", m_Sc.RemoteEndPoint);
try
{
while (true)
{
txt = strmRd.ReadLine();
Console.WriteLine("Msg: {0}", txt);
txt += " Echo!! \r\n";
strmWr.Write(txt); strmWr.Flush();
}
}
catch (Exception ex)
{
Console.WriteLine("Exception in TalkWithClient");
}
Console.WriteLine("{0} Disconnected", m_Sc.RemoteEndPoint);
m_Sc.Close(); strm.Close(); strmRd.Close(); strmWr.Close();
return;
}
}
}
And here is the java code:
package com.example.mogri.tcpsocket;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText ettext;
private TextView tvlog;
TcpClient mTcpClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ( ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.INTERNET},225);
}
if ( ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_NETWORK_STATE},225);
}
ettext = (EditText) findViewById(R.id.etText);
tvlog = (TextView) findViewById(R.id.tVlog);
Button btnsend = (Button) findViewById(R.id.btnsend);
btnsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String input = ettext.getText().toString();
mTcpClient.sendMessage(input);
log(input);
}
});
new ConnectTask().execute("");
}
public void log(String add){
tvlog.setText( tvlog.getText()+"\n"+add);
}
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//response received from server
Log.d("test", "response " + values[0]);
//process server response here....
}
}
}
The tcpclient class:
package com.example.mogri.tcpsocket;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
* Created by mogri on 01.04.2017.
*/
public class TcpClient {
public static final String SERVER_IP = "192.168.1.1"; //server IP address
public static final int SERVER_PORT = 13;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
public void sendMessage(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
/**
* Close the connection and release the members
*/
public void stopClient() {
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_PORT);
try {
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
while (mRun) {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}

Android socket principle and exception

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);
}
}
}

android client-java server communication

We are developing an android application.It basically involves client server communication.Client is android phone and server is java.Client and server communication takes place.It is expected that client sends a message to the server and server responds back to the client.But in reality client is able to send the message to the server but server is unable or sends an incorrect response.I don't understand why is it happening.
Here is the client code(android):
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
public TextView accept;
private Button button;
private String message;
private static BufferedReader bufferedReader;
public static InputStreamReader inputStreamReader;
String response;
DataInputStream dis;
static String Extra_message = "hkrw.clientside";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1);
button = (Button) findViewById(R.id.button1);
this.accept = (TextView) findViewById(R.id.accept);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
message = textField.getText().toString();
textField.setText("");
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
accept.setText(response);
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
DataOutputStream dataOutputStream = null;
DataInputStream smalldataInputStream = null;
try {
client = new Socket("192.168.1.6", 4446);
printwriter = new PrintWriter(client.getOutputStream(), true);
inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
printwriter.write(message);
// smalldataInputStream = new DataInputStream(client.getInputStream());
printwriter.flush();
printwriter.close();
//dis= new DataInputStream(client.getInputStream());
//response=dis.readUTF();
response = bufferedReader.toString();
client.getInputStream();
// client.shutdownInput();
// client.shutdownOutput();
client.close();
} 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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the code of the new activity which I have created in client side.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class respond extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_respond);
Intent intent=getIntent();
String message = intent.getStringExtra(MainActivity.Extra_message);
TextView response;
response= (TextView) findViewById(R.id.textView1);
response.setText(message);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_respond, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the server code in java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.DataOutputStream;
public class Server {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static PrintWriter printwriter ;
static DataOutputStream dos;
public static void main(String[] args) {
String w="Hello World";
try {
serverSocket = new ServerSocket(4446); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4446");
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(message);
dos=new DataOutputStream(clientSocket.getOutputStream());
dos.writeUTF(w);
clientSocket.close();
System.out.println(dos);
inputStreamReader.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
this example sends a message to the server (pc in wlan),
and then gets the message back from server to phone, changing text accordingly.
change ip address of server to your pc address in wlan,
make sure to start server first, then phone app, being in that wlan
Server:
public class ChatServer implements Runnable{
private Socket socket = null;
private ServerSocket server = null;
private Thread thread = null;
private DataInputStream streamIn = null;
private DataOutputStream streamOut = null;
int port;
boolean done ;
public ChatServer(){
port = 6668;
try{
System.out.println("Gewählter Port: " + port + ", bitte warte...");
server = new ServerSocket(port);
System.out.println("Server gestartet: " + server);
start();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
public void start(){
if (thread == null){
thread = new Thread(this);
thread.start();
}
}
public void run(){
while (thread != null){
try{
System.out.println("waiting for Client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket + " IP: "+ socket.getInetAddress());
System.out.println("connecting ...");
open();
done = false;
while (!done){
try{
String line = streamIn.readUTF();
System.out.println(line);
send("Server recieved :"+line);
done = line.equals(".bye");
}
catch(IOException ioe){
done = true;
ioe.printStackTrace();
}
}
close();
}
catch(IOException ie){
System.out.println("Acceptance Error: " + ie);
}
}
}
public void send(String msg)
{
try
{
if(msg != null) {
streamOut.writeUTF(msg);
streamOut.flush();
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public void open() throws IOException{
streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
streamOut = new DataOutputStream(socket.getOutputStream());
}
public void close() throws IOException{
if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
if (streamOut != null) streamOut.close();
}
#SuppressWarnings("deprecation")
public void stop(){
if (thread != null){
thread.stop();
thread = null;
}
}
}
client:
public class MainActivity extends Activity implements Runnable{
EditText textUnten;
Button button;
ChatProzKlasse chat;
public static String puffer;
public static String messages;
public static TextView textMitte;
Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textMitte = (TextView) findViewById (R.id.textMitteID);
textUnten = (EditText) findViewById (R.id.textUntenID);
button = (Button) findViewById(R.id.sendButton);
messages = "";
chat = new ChatProzKlasse();
thread = new Thread(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chat.client.send(textUnten.getText().toString());
textUnten.setText("");
}
});
thread.start();
}
public void setTextMitte(){
runOnUiThread(new Runnable() {
#Override
public void run() {
textMitte.setText(messages);
}
});
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void run() {
while(true) {
setTextMitte();
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ChatClient {
private Socket socket = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
private DataInputStream streamIn = null;
public static boolean isconnected = false;
public ChatClient(String serverName, int serverPort){
System.out.println("Verbindungsaufbau. Bitte warten ...");
try{
socket = new Socket(serverName, serverPort);
Log.d("DEBUG", "Connected: " + socket);
if(socket != null) {
start();
}
}
catch(UnknownHostException uhe){
Log.d("DEBUG","Host unknown: " + uhe.getMessage());
}
catch(IOException ioe){
Log.d("DEBUG","Unexpected exception: " + ioe.getMessage());
}
}
public void start() throws IOException
{
console = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
isconnected = true;
}
public void stop(){
try{
if (console != null) console.close();
if (streamOut != null) streamOut.close();
if (socket != null) socket.close();
}
catch(IOException ioe){
System.out.println("Error closing ...");
}
}
public void open() throws IOException{
streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException{
if (socket != null) socket.close();
if (console != null) console.close();
}
public void send(String msg)
{
try
{
if(msg != null) {
streamOut.writeUTF(msg);
streamOut.flush();
}
}
catch(IOException ioe)
{
Log.d("DEBUG","Sending error: " + ioe.getMessage());
}
}
public void recieve(){
try{
open();
boolean done = false;
while (!done){
try{
String line = streamIn.readUTF();
if(!(line.equals(""))) {
MainActivity.messages =line;
MainActivity.puffer = line;
}
System.out.println(" " + line);
done = line.equals(".bye");
}
catch(IOException ioe){
done = true;
ioe.printStackTrace();
}
}
close();
}
catch(IOException ie){
System.out.println("Acceptance Error: " + ie);
}
}
}
public class ChatProzKlasse implements Runnable {
Thread thread;
ChatClient client;
public ChatProzKlasse(){
thread = new Thread(this);
thread.start();
}
#Override
public synchronized void run() {
if(client == null) {
try {
System.out.println(" trying new Client");
client = new ChatClient("192.168.1.111", 6668);
} catch (Exception e) {
e.printStackTrace();
}
}
if (client !=null){
if(client != null && ChatClient.isconnected) {
client.recieve();
}
}
}}

how can i send my message from android client to other android client using my socket java PC server

i have my code that sucessfuly send my client message to server.. can anyone help pls ? i'm new in socket programming. i want to establish a server that sends the message of my android client to other android client... here is my code
CLIENT ANDROID :
package com.example.websocketclient;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Chatroom extends Activity {
public static String msgToServer = null;
TextView uname;
EditText in;
Button snd;
TextView out;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatroom);
uname = (TextView) findViewById(R.id.textViewmynam);
in = (EditText) findViewById(R.id.editTextInput);
snd = (Button) findViewById(R.id.buttonSend);
out = (TextView) findViewById(R.id.textViewOutput);
Bundle bundle = getIntent().getExtras();
String urname = bundle.getString("myname");
uname.setText(urname);
MyClientTask clientTask = new MyClientTask();
clientTask.execute();
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
connect();
return null;
}
}
public void connect() {
Socket sock;
int[] allports = {1111,1919,2020};
int portnum;
for(int i=1;i<allports.length;i++) {
try {
portnum = allports[i];
boolean socketno = Middleware.available(portnum);
String ad = "192.168.149.1";
if(socketno = true) {
sock = new Socket(ad,portnum);
while(socketno) {
sendmsg(sock);
}//while
// sock.close();
}//if
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendmsg (final Socket s) {
snd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//boolean listening = true;
String inmsg = ""+in.getText().toString();
String response = "";
msgToServer = inmsg;
//out.append("you:"+msgToServer+"\n");
try {
DataOutputStream outToServer = new DataOutputStream(s.getOutputStream());
DataInputStream inToServer = new DataInputStream(s.getInputStream());
if(outToServer != null){
outToServer.writeBytes(msgToServer+"\n");
}
}
catch (Exception e) {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chatroom, menu);
return true;
}
}
Here is my PC Server side :
package Server;
import java.net.*;
import java.io.*;
import java.util.Scanner;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;
public class SocketServer extends Thread {
final static int _portNumber = 1919; //Arbitrary port number
public static void main(String[] args)
{
try {
new SocketServer().startServer();
} catch (Exception e) {
System.out.println("I/O failure: " + e.getMessage());
}
}
public void startServer() throws Exception {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(_portNumber);
} catch (IOException e) {
System.err.println("Could not listen on port: " + _portNumber);
System.exit(-1);
}
while (listening) {
System.out.println("Huwat huwat kang client..!");
handleClientRequest(serverSocket);
}
serverSocket.close();
}
private void handleClientRequest(ServerSocket serverSocket) {
try {
new Thread(new ConnectionRequestHandler(serverSocket.accept())).start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Handles client connection requests.
*/
public class ConnectionRequestHandler implements Runnable{
private Socket _socket;
private PrintWriter _out;
private BufferedReader _in;
public ConnectionRequestHandler(Socket socket) {
_socket = socket;
}
public void run() {
String info;
int maxid;
System.out.println("Client connected to socket: " + _socket.toString());
info = _socket.toString();
//incrementing the msg_id
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
_socket.getOutputStream()));
_in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
String inputLine;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/finalclient","root","");
PreparedStatement st = con.prepareStatement("select *from msgs order by msg_id desc");
ResultSet r1 = st.executeQuery();
r1.first(); // or r1.next()
maxid = r1.getInt("msg_id") + 1;
while ((inputLine = _in.readLine()) != null) {
System.out.println("Message from Client: "+inputLine);
out.write(inputLine);
try {
PreparedStatement st1=con.prepareStatement("insert into msgs values(?,?,?)");
st1.setInt(1,maxid);
st1.setString(2,info);
st1.setString(3,inputLine);
int count = st1.executeUpdate ();
System.out.println (count + " rows were inserted to Database");
}
catch (Exception e) {
System.out.println("Failed to Insert from DB"+e);
}
}
}
catch (Exception e) {
System.out.println("Failed to Select from DB"+e);
}
}
}
}

Android. Sockets. Fail Connection

I develop simple client-server app for Android by examples:
http://android-er.blogspot.com/2014/02/android-sercerclient-example-server.html
http://android-er.blogspot.com/2014/02/android-sercerclient-example-client.html
Server code:
package com.example.androidserversocket;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
infoip.setText(getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Android, you are #" + cnt;
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replayed: " + msgReply + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
}
}
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;
}
}
Client code:
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView)findViewById(R.id.response);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
textResponse.setText("");
}});
}
OnClickListener buttonConnectOnClickListener =
new OnClickListener(){
#Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException 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 {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
I work with TWO emulators Android.
When server starts it gets IP: 10.0.2.15
And in Client window I set IP: 10.0.2.15 and PORT:8080.
But I get exception: "Failed to connect to /10.0.2.15 (port 8080): connect failed: ECONNREFUSED (Connection refused)"
Why I can not connect?
Just to recap this as an answer: Testing on a real device should solve the issue. Apps generally have to be tested on at least one (better several) real device. Especially trying to connect an emulator to another emulator on the same PC is not even remotely close to a real situation. One device would be enough for you. That is, a real Android can connect to an emulator or the other way round as long as the PC allows the connection.

Categories