I run an application in Android and a string value as an answer. Now I want to pass this result to the Java server which is on my localhost, i.e pass the value from Android code to Java desktop application.
I tried using this code, but when I run the client it says unfortunately the application has stopped.
It says:
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
libcore.io.IoBridge.connectErrno(IoBridge.java:127)
I found from somewhere that I need to use asynctask for it. Can you please guide me on how to use asynctask here?
The IP address is my localhost's IP and port number is any random number.
I try to run the server and then the client. I even tried running client on emulator and on the actual device. The app closes. I am new to Android. What I am doing wrong?
Here's the code of the client:
package com.example.client;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1); //reference to the text field
button = (Button) findViewById(R.id.button1); //reference to the send button
//Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
messsage = textField.getText().toString(); //get the text message on the text field
textField.setText(""); //Reset the text field to blank
try {
client = new Socket("10.0.2.2", 4444); //connect to 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();
}
}
});
}}
And here's the code of the server:
public class server {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
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(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
The Async Task code :
package com.example.client;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1); //reference to the text field
button = (Button) findViewById(R.id.button1); //reference to the send button
//Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
messsage = textField.getText().toString(); //get the text message on the text field
textField.setText(""); //Reset the text field to blank
try {
client = new Socket("134.190.162.165", 44440); //connect to 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();
}
}
});
}
}
Use this on the PC side to get its IP:
String IPfromPC = InetAddress.getLocalHost().getHostAddress();
Use that IP in your Andoid app:
mSocket.connect(new InetSocketAddress(IPfromPC, 4444), 5000);
Related
I made a super simple server on my Windows Machine that waits for a client, and when connected, all it does is get a message and prints it to the Console.
When I run a Server code on my computer, and then run another Client application, it works fine. However, when I run the exact same client code(except for a few changes that are necessary) on my Android Phone(connected via USB), it doesn't work.
The IP address for my PC is correct and the port is free, I've been getting this error message:
W/System.err: java.net.ConnectException: failed to connect to /192.168.10.104 (port 1755) from /:: (port 42102): connect failed: ETIMEDOUT (Connection timed out)
My server.java that runs on my PC is
import java.net.*;
import java.io.*;
public class Server {
// Initialize everything
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in =null;
//constructor with port
public Server(int port) {
try {
server = new ServerSocket(port);
System.out.println("Server started, waiting for Client...");
socket = server.accept();
System.out.println("Client accepted");
in =new DataInputStream(new BufferedInputStream(socket.getInputStream()));
String line = "";
while (!line.equals("Over")) {
try {
line = in.readUTF();
System.out.println(line);
}
catch(IOException e) {
System.out.println(e);
}
}
System.out.println("Closing connection");
//CLosing connections
socket.close(); in .close();
}
catch(IOException e) {
System.out.println(e);
}
}
public static void main(String[] args) {
Server server = new Server(1755);
}
}
This is the client code
import java.io.*;
import java.net.*;
public class MainActivity extends AppCompatActivity {
TextView Message_shower;
EditText text_place;
TextView messageStatus;
Button send_btn;
// Initialize sockets and IO streams
Socket socket = null;
DataOutputStream out = null;
private static final int SERVERPORT = 1755;
private static final String SERVER_IP = "192.168.10.104";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_place = findViewById(R.id.editText);
messageStatus = findViewById(R.id.messageStatus);
send_btn = findViewById(R.id.send_btn);
// Shows recent sent message
Message_shower = findViewById(R.id.Message_shower);
// Establish a connection
send_btn.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View view) {
new Sender().execute();
}
});
}
// Close connections
private void onClose() {
try {
if (socket != null) {
out.close();
socket.close();
}
}
catch(IOException e) {
System.out.println(e);
}
}
class Sender extends AsyncTask < Void,
Void,
Integer > {
private Exception e1;
private Exception e2;
String input;
#Override
protected void onPreExecute() {
EditText text_place = findViewById(R.id.editText);
// Takes input from terminal
input = text_place.getText().toString();
Message_shower.setText(input);
System.out.println("Reached here\n");
}
#Override
protected Integer doInBackground(Void...params) {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
// Sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(Exception e) {
this.e1 = e;
}
try {
out.writeUTF(input);
} catch(Exception h) {
this.e2 = h;
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (e1 != null) {
e1.printStackTrace();
}
if (e2 != null) {
e2.printStackTrace();
}
TextView txt = findViewById(R.id.messageStatus);
txt.setText("Message Sent");
text_place.setText("");
onClose();
}
}
}
All input is very appreciated, I've tried various ways like turning off the firewall and such but none worked.
Here I created a fan activity and every time when I Click to any button
It Start Fan-Socket class and create a new Socket on every click button.
But I am getting a delay when I Click buttons continueosly.
how can I Send a multiple request using single Socket and on each button
click how can I send a msg string through the Socket??
Is there is Something that creating a buffer and putting a value in
that buffer and call each buffer value on every click.
if it so How can I do that.. ??
Kindly help me to solve this issue as
I am new in android programming I can not able to solve this problem
from several day
Fan Activity:
public class FAN extends AppCompatActivity {
private Button buttonOn;
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_fan);
buttonOn = (Button) findViewById(id.Buttonon);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
buttonOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (turnOn) {
int tmpInt = 2;
String FAN = String.valueOf(tmpInt); //Converting int to string.
FAN_SOCKET b1 = new FAN_SOCKET(); // calling class fan socket
b1.execute(FAN); //calling fan-socket class and pass the the 2 value through it.
turnOn = false;
}
else {
int tmpInt = 0;
String FAN = String.valueOf(tmpInt); //Converting int to string.
FAN_SOCKET b1 = new FAN_SOCKET(); // calling class fan socket
b1.execute(FAN); //sending value to socket.
turnOn = true;
}
}
});
Fan-Socket Class:
class FAN_SOCKET extends AsyncTask<String,Void,String>{
Socket socket = null;
PrintWriter pw;
String response;
#Override
protected String doInBackground(String... voids) {
String massage = null;
try {
massage = voids[0];
socket = new Socket("192.168.0.79",8888 );
pw = new PrintWriter(socket.getOutputStream());
pw.write(massage);
try {
pw.flush();
pw.close();
socket.close();
} catch (SocketException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
I'm trying to send commands from my phone to my computer using Sockets.
I've tryed the answers here:
Android and PC Socket connection
But after some digging i found out that you need to use a Async task so i tryed this:
Using AsyncTask for android network connection
But for some reason my socket times out. Is there a way to find out why? because from the error i can't tell:
The error from Logcat:
And this is the client code:
public class MainActivity extends AppCompatActivity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String message;
private static final int SERVERPORT = ####;
private static final String SERVER_IP = "########";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
}
public void onClick(View view) {
message = textField.getText().toString();
textField.setText(""); // Reset the text field to blank
new AsyncAction().execute();
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
System.out.println("background running");
System.out.println(message);
client = new Socket(SERVER_IP, SERVERPORT); // connect to server
System.out.println(client.isConnected());
System.out.println("test");
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(message); // 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;
}
}
}
I wrote a Server for this in Java and tested it in the emulator.
I had two things to do :
The server IP is "10.0.2.2" if you are using an Android Emulator. LocalHost is de Emulator Virtual Machine.
Your application needs Permission Internet in manifest
Here is the server Code
/**
*
* #author Jean-Pierre
*/
public class SocketServer {
private static final int portnumber = 4444;
public static void main(String[] args) {
SocketServer socketServer = new SocketServer();
socketServer.run();
}
/**
* Reads a String from the client
* Converts it to Uppercase
* and sends it Back.
*/
private void run() {
try {
ServerSocket serverSocket = new ServerSocket(portnumber);
Socket clientSocket = serverSocket.accept();
System.out.println("connected with :" + clientSocket.getInetAddress());
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
InputStreamReader is =
new InputStreamReader(clientSocket.getInputStream());
BufferedReader in =
new BufferedReader(is);
while (true) {
String line = in.readLine();
if (line != null) {
System.out.println("recieved:" + line);
out.println(line.toUpperCase());
}
}
} catch (IOException ex) {
Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I tried to write a simple server for an app that user can write a message from PC using telnet to IP and port. IT works just fine and it can show the
The problem is, when user closes telnet window (CMD window in PC, there is where user connects to app) the app stops.
Is there a way to prevent this behaviour? Here is my code:
//Defined in Activity class
//Sockets, servers, clients and stuff
public java.net.ServerSocket MyServerSocket;
public String IpAddress = "";
public int Port = 12345;
public Handler UpdateConversationHandler;
public Thread ServerThread = null;
Nested classes inside the Activity class:
class ServerThread implements Runnable{
public final String IpAddress;
public final int Port;
public ServerThread(String ipAddress, int port)
{
IpAddress = ipAddress;
Port = port;
}
public void run() {
Socket socket = null;
try{
MyServerSocket = new ServerSocket(Port);
} catch (IOException e) {
e.printStackTrace();
}
while(!Thread.currentThread().isInterrupted()){
try{
socket = MyServerSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable
{
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
try{
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e){
e.printStackTrace();
}
}
public void run() {
while(!Thread.currentThread().isInterrupted()){
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() {
_textview_info.setText("Client Says: "+ msg );
}
}
I also have this code for onStop method, but it doesn't help!
#Override
protected void onStop() {
super.onStop();
//Closing server socket
try
{
MyServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And this is the onCreate method, where the server starts:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_context = this;
//Prepare spinners
_preferences = getSharedPreferences("org.pervasivesystems.nexusmosaic", MODE_PRIVATE);
_preferencesEditor = _preferences.edit();
_spinner_videos = (Spinner) findViewById(R.id.spinner_select_video);
_spinner_ids = (Spinner) findViewById(R.id.spinner_select_id);
populateSpinners();
//Prepare server
IpAddress = getIpAddress();
TextView tvIpAddress = (TextView) findViewById(R.id.textview_ip_address_value);
tvIpAddress.setText(IpAddress);
_textview_info = (TextView) findViewById(R.id.textview_information);
UpdateConversationHandler = new Handler();
ServerThread = new Thread(new ServerThread(IpAddress, Port));
this.ServerThread.start();
}
UPDATE
When I start the app, even before connecting from PC to app using telnet, I get the following message continuesly in LOGCAT:
11-14 15:45:32.460 W/System.err? at java.lang.Thread.run(Thread.java:856)
11-14 15:45:32.460 W/System.err? java.net.SocketException: Socket is closed
11-14 15:45:32.460 W/System.err? at java.net.ServerSocket.checkOpen(ServerSocket.java:362)
11-14 15:45:32.460 W/System.err? at java.net.ServerSocket.accept(ServerSocket.java:120)
11-14 15:45:32.460 W/System.err? at .MainActivity$ServerThread.run(MainActivity.java:233)
Line 233 is refering to this code:
while(!Thread.currentThread().isInterrupted()){
try{
socket = MyServerSocket.accept(); //LINE 233
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
I also found out that after closing the telnet window from PC, the UpdateUiThread keeps running.
What is probably happening is that your communication thread is noticing the terminated connection and exits. This is how you wrote it. Im not sure what you want it to do instead...
If you want to do something after the terminated connection, just put some code right after
while(!Thread.currentThread().isInterrupted()){ ... }
Wait for the thread to finish, then do what you want.
Sometimes it helps me to add some system outs throughout threaded code to get a handle of when things are firing off/ending. It will help, trust me.
Try this
do{
if(!Thread.currentThread().isInterrupted()){
try{
socket = MyServerSocket.accept();
if(socket!=null && socket.isConnected()){
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}while(socket!=null && socket.isConnected());
I'm new at developing at android OS. I try developing my telnet client for android OS.
Now, I only try to connect telnet server, and receive login message.
But when I start socket to connect telnet server Ihave received strange symbols ??????!???? instead the logon message from telnet server.
public class MainActivity extends Activity {
protected static final int TCP_SERVER_PORT = 23;
protected String inMsg, str;
static Editable sentence;
static String modifedSentence;
BufferedReader inFromUser;
Socket clientSocket = null;
DataOutputStream outToServer=null;
BufferedReader inFromServer=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button)findViewById(R.id.startButton);
final TextView textView = (TextView)findViewById(R.id.textView);
startButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
new Thread(new Runnable() {
#Override
public void run() {
//Create socket
try {
clientSocket = new Socket("192.168.1.1",23);
//Create out stream for ClientSocket
outToServer = new DataOutputStream(clientSocket.getOutputStream());
//Create ib stream for ClientSocket
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Receive login message from telnet server
modifedSentence = inFromServer.readLine();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Update UI activity with login message
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(modifedSentence);
}
});
}
}).start();
}
});
}
protected void onDestroy()
{
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
These "strange" symbols ??????!???? mean, that you use wrong encoding. When you create InputStreamReader you should explicitly point which encoding this stream should use. I don't known which encoding is used inside your telnet service, but you can try various of them, e.g. windows-1252:
new InputStreamReader(clientSocket.getInputStream(), Charset.forName("windows-1252"))
Telnet app require telnet protocol for connections to the telnet server. It's not a simple tcp connection. I use apache commonse library which provide class for telnet accessing.
Thanks