Android device to Server text send - android

I am trying to send a string from an android device to the server using the code following:
package com.example.androidsocketserver;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
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.widget.EditText;
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "10.50.27.10";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
But it is sending the string only on first click. In second time it is unable to send the content. What I need to do?

But it is sending the string only on first click. In second time it is
unable to send the content. What I need to do?
Put new Thread(new ClientThread()).start(); in a separate method say:
startThread(){
new Thread(new ClientThread()).start();
}
and then call this method in onClick

Related

How to get message to send from server to Android

I have made a program to send a message from a client to a server(2 android devices), but the message is not being sent.
Here is the code of the client side application:
package com.example.clientphone;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.*;
public class MainActivity extends ActionBarActivity {
private EditText ipaddress , textfield;
private Button send;
private String ip , message;
private Socket client;
private PrintWriter printwriter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText)findViewById(R.id.editText1);
textfield = (EditText)findViewById(R.id.editText2);
send = (Button) findViewById(R.id.button1);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();// enabling strict mode and setting thread policy
StrictMode.setThreadPolicy(policy);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = textfield.getText().toString();
ip = ipaddress.getText().toString();// getting ip address
textfield.setText(" ");
try {
client = new Socket(ip, 5200);// ip address is entered over here....
printwriter = new PrintWriter(client.getOutputStream() , true);// getting the outputstream
printwriter.write(message);// writing the message
printwriter.flush();// flushing the printwriter
printwriter.close();// closing printwriter
client.close();// closing client
} catch (UnknownHostException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
});
}
}
Here is the code for server side application. I have chosen the port 5200 to connect on. I want the user to enter the IP address of the other device and not keep it hard-coded:
package com.example.serverphone;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
public class MainActivity extends ActionBarActivity {
TextView message;
private ServerSocket socket;
private Handler UpdateConversationHandler;
Thread ServerThread = null;
public static final int port = 5200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (TextView)findViewById(R.id.textView1);
UpdateConversationHandler = new Handler();
this.ServerThread = new Thread(new ServerThread());
this.ServerThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable{
#Override
public void run() {
Socket socket2 = null;
try {
socket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
while(!Thread.currentThread().isInterrupted()){
try {
socket2 = socket.accept();
BufferedReaderThread commThread = new BufferedReaderThread(socket2);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class BufferedReaderThread implements Runnable{
private Socket clientSocket;
private BufferedReader input;
public BufferedReaderThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while(!Thread.currentThread().isInterrupted()){// making sure the thread is not interrupted...
try {
String read = input.readLine();
if(read != null){
UpdateConversationHandler.post(new updateUIConversation(read));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIConversation implements Runnable{
private String msg;
public updateUIConversation(String str){
this.msg = str;
}
#Override
public void run() {
message.setText(message.getText().toString() + msg + "/n");
}
}
}
In your client you are doing network operation on the main thread. Do them in a separate thread. Do not silently supress exceptions and you will see in the log.
new Thread(new Runnable() {
public void run() {
try {
Socket client = new Socket(ip, 5200);
PrintWriter = new PrintWriter(client.getOutputStream() , true);
printwriter.write(message);// writing the message
printwriter.flush();// flushing the printwriter
printwriter.close();// closing printwriter
client.close();// closing client
} catch (Exception x) { Log.e("CLIENT", "Exception " + x); }
}).start();

How to send message from server to client (TCP , android applications)

I had created two android applications connected with sockets. Client sends an image to server and Server displays it. when you touch the image on server, it gets its coordinates,this is working now. what I need is that server sends the coordinates to the client, but I dont know how to send them to client and retrieve them, should I open a new socket ? I have no idea how to do this. Can somebody give me a hand please?
This is my code so far
SERVER
package com.example.serverlate;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.TextView;
public class ServerLate extends Activity {
private ServerSocket serverSocket;
String touchedCoordinates;
Handler updateConversationHandler;
Thread serverThread = null;
private ImageView imageView;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_late);
imageView=(ImageView) findViewById(R.id.imageViewServer);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private DataInputStream input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
InputStream in = this.clientSocket.getInputStream();
this.input = new DataInputStream(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
byte[] data;
int len= this.input.readInt();
data = new byte[len];
if (len > 0) {
this.input.readFully(data,0,data.length);
}
updateConversationHandler.post(new updateUIThread(data));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private byte[] byteArray;
public updateUIThread(byte[] array){
this.byteArray=array;
}
#Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray .length);
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
touchedCoordinates="Touch coordinates : " +
String.valueOf(event.getX()) + " x " + String.valueOf(event.getY());
return true;
}
});
}
}
}
CLIENT
package com.example.clientlate;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
public class ClientLate extends Activity {
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.2.2";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_late);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
ImageView imageView=(ImageView) findViewById(R.id.imageView1);
Bitmap bmp=((BitmapDrawable)imageView.getDrawable()).getBitmap();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] array = bos.toByteArray();
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(array.length);
dos.write(array, 0, array.length);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
You can try something like this in client side :
public class ClientLate extends Activity {
public void onCreate(Bundle savedInstanceState) {
....
updateConversationHandler = new Handler();
FPSHandler = new Handler();
new Thread(new ClientThread()).start();
....
}
class ClientThread implements Runnable {
#Override
public void run() {
thread1=Thread.currentThread();
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socketTE = new Socket(serverAddr, SERVERPORT);
CommunicationThread commThread = new CommunicationThread(socketTE);
new Thread(commThread).start();
} catch (UnknownHostException e1) {
Toast.makeText(getApplicationContext(), "Connection failed",
Toast.LENGTH_SHORT).show();
finish();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(), "Connection failed",
Toast.LENGTH_SHORT).show();
finish();
}
}
}
class CommunicationThread implements Runnable
{
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket)
{
thread2=Thread.currentThread();
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
while (running.get())
{
try
{
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable
{
private String msg;
public updateUIThread(String str)
{
this.msg = str;
}
#Override
public void run()
{
...
}
}
....
}

Android Client-server message exchanging is slow

I have a working messaging app that sends messages from the client to the server.
I want the client to CONSTANTLY listen for messages from the server.
I want the client to only send packets to the server when "Start" is called, but the problem is that I have to press it twice for the message to actually deliver to the server (Idk why)
Later on I'll change the program to something that always delivers messages to the server (his GPS location), so I would also like some tips about how to make a loop in an Android app.
//Client
package com.example.clienttest;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Thread m_objThreadClient;
Socket clientSocket;
TextView serverMessage;
EditText clientMessage;
String sIn, sOut;
BufferedReader brOut, brIn;
DataOutputStream oos;
DataInputStream ois;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverMessage = (TextView) findViewById(R.id.textView1);
clientMessage = (EditText) findViewById(R.id.editText1);
m_objThreadClient = new Thread( new Runnable(){
public void run()
{
try {
clientSocket = new Socket("192.168.1.102", 4000);
oos = new DataOutputStream (clientSocket.getOutputStream());
ois = new DataInputStream (clientSocket.getInputStream());
brIn = new BufferedReader (new InputStreamReader(ois));
} catch (IOException e) {
serverMessage.setText(e.getMessage());
}
}
});
m_objThreadClient.start();
}
public void Listener(){
try {
while ((sIn = brIn.readLine()) != null){
sIn = brIn.readLine();
}
serverMessage.setText(sIn);
} catch (IOException e) {
serverMessage.setText(e.getMessage());
}
}
public void Start(View view) {
sOut = clientMessage.getText().toString();
try {
oos.writeUTF(sOut);
oos.flush();
oos.flush();
} catch (IOException e) {
serverMessage.setText(e.getMessage());
}
}
public void onStop(){
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//Server
import java.net.ServerSocket;
import java.net.Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.Hashtable;
public class Server2 {
#SuppressWarnings("resource")
public static void main (String[] args) throws IOException {
ServerSocket server = null;
try {
server = new ServerSocket(4000);
} catch (IOException e) {
System.err.println("Could not start up on: " + "4000" + "Maby server is already open? Or a portforwording messup?");
System.err.println(e);
System.exit(1);
}
Socket client = null;
while(true) {
try {
client = server.accept();
System.out.print("Connected ");
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
}
Thread t = new Thread(new ClientConn(client));
t.start();
}
}
}
class ClientConn implements Runnable {
private Socket client;
String Recv;
DataInputStream inFromClient;
DataOutputStream outToClient;
ClientConn(Socket client) {
this.client = client;
try {
inFromClient = new DataInputStream(client.getInputStream());
outToClient = new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String response;
try {
while ((response = inFromClient.readUTF()) != null) {
Recv = inFromClient.readUTF();
System.out.print("Msg: " + Recv + " \n");
if( Recv.equals("Hi")){
outToClient.writeUTF("Wa alaikum");
outToClient.flush();
}
else{
outToClient.writeUTF("..what?");
outToClient.flush();
}
}
} catch (IOException e) {
System.out.print("No input ");
System.err.println(e);
}
}
}

Android socket NullPointerException

I have problem with android sockets , I have two android applications Server and ServerClient , in ServerClient It gives nullPointerException on second row written below
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
I checked serverAddr is 10.0.2.2 , but then I saw that socket is null. Can anybody helps with it?
EDIT: with this serverAddress I saw that it is unreachable, maybe I must make it reachable manual ?
here is sources
*ServerClient*
package com.example.serverclient;
import android.os.Bundle;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import android.view.Menu;
public class MainActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "10.0.2.2";
private static final int REDIRECTED_SERVERPORT = 5000;
// AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
// PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
// PORT 6000
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
OutputStream sk = socket.getOutputStream();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
} catch (UnknownHostException e) {
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
tv.setText("Error3");
e.printStackTrace();
}
}
});
}
}
**Server**
package com.example.myserver;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText("Nothing from client yet");
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText(mClientMsg);
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT );
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Have you made sure that you aren't getting an UnknownHostException or a IOException? One of those has to be getting called otherwise socket would not be null.
Change (Exception e) of the error 3 para to NullPointerException and then run the client side and send a message. Error 3 will no longer be displayed on the screen and you will receive the message on Myserver.
Exception e --> NullPointerException
This class returns your response, but also needs permission of internet in manifest file.
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
mSocket = IO.socket("http://chat.socket.io");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}

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.

Categories

Resources