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);
}
}
}
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.
Good day, I am developing an android app to send textView value to a server made in Java netbeans, I followed a tutorial on YouTube [https://www.youtube.com/watch?v=29y4X65ZUwE ] however when I run the server first it does not send the data through. I am connected to the same Wi-Fi network as well.
EDIT: When I use the code System.out.println(ss.getInetAddress()); in my server class in Java, I get 0.0.0.0 as the ip address but I am connected to a wifi network.
Here is my AsyncTask class (written in android studio):
public class SendData extends AsyncTask<String, Void, Void> {
Socket s;
DataOutputStream dos;
PrintWriter pw;
#Override
protected Void doInBackground(String... voids) {
String number = voids[0];
try{
s = new Socket("196.248.139.178", 6000);
pw = new PrintWriter(s.getOutputStream());
pw.write(number);
pw.flush();
pw.close();
s.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
return null;
}
}
Here is my MainActivity(called it the Orders class, written in android studio):
public class Orders extends AppCompatActivity {
Button send;
EditText orderNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orders);
orderNum = findViewById(R.id.orderNum);
send = findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendData numSender = new SendData();
numSender.execute(orderNum.getText().toString());
}
});
}
}
The following is my Server Code written in NetBeans, it includes a JFrame with a JTextArea to display to data sent from android phone:
public class OrderList extends javax.swing.JFrame {
static Socket s;
static ServerSocket ss;
static InputStreamReader isr;
static BufferedReader br;
static String numbers;
/**
* Creates new form OrderList
*/
public OrderList() {
initComponents();
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OrderList().setVisible(true);
}
});
try{
ss = new ServerSocket(6000);
while(true){
s = ss.accept();
isr = new InputStreamReader(s.getInputStream());
br = new BufferedReader(isr);
numbers = br.readLine();
System.out.println(numbers);
// orderNumList is the text area where data is going to be set.
if(orderNumList.getText().equals("")){
orderNumList.setText(numbers);
}
else{
orderNumList.setText(orderNumList.getText()+ "\n" + numbers);
}
}
}catch(IOException e){
e.printStackTrace();
}
}
Any advice and help will be highly appreciated.
Try to read char by char because reading line by line can block.
Check that : BufferedReader, detecting if there is text left to read
Also check if Windows Firewall does not block the communication.
I'm attempting to use my android phone as a keyboard for my PC.
This is done over a local WiFi connection using sockets to create the client/server connection.
I'm using a textwatcher to pick up the change in characters in an editText and then sending those over to the server which then uses a robot class to write that onto the PC. This is all using a Softkeyboard on the android phone.
The issue is that when writing in editText only one character gets sent. and picked up by the server.
e.g. I type on the android phone "a" and the respective keypress will be simulated on the server. If I then type another character it does not read that character but if I delete the "a" and then type another character it will send that character.
Below is the Client side of the code, the Android application.
public class MainActivity extends AppCompatActivity implements View.OnKeyListener {
private final static int portNumber = ****;
private final static String hostName = "192.168.0.8";
private final static String cTest = "Connection Test";
Socket socket = null;
private static String TAG = "test";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
#Override
public void run() {
try {
Log.i(cTest, "attempting to connect");
socket = new Socket(hostName, portNumber);
Log.i(cTest, "Connected");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Connected Successfully", Toast.LENGTH_SHORT).show();
}
});
EditText editText = (EditText)findViewById(R.id.editText);
editText.addTextChangedListener(editTextWatcher);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(cTest, e.getMessage());
}
}
}.start();
}
private TextWatcher editTextWatcher = new TextWatcher() {
private void sendTextToServer(String send) {
BufferedWriter bw = null;
String textChange = send;
try {
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(textChange);
bw.newLine();
bw.flush();
} catch (IOException e) {
}
}
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
Log.d(TAG, s + " Character Read");
String test = s.toString();
this.sendTextToServer(test);
}
};
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
}
The following code is the server side code which is being done in eclipse.
public class ListenServerMain {
private static boolean ifConnected = true;
private final static int portNumber = ****;
public static String readIn;
private static Socket client = null;
private static ServerSocket server = null;
private static BufferedReader in = null;
private static Robot robot = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
robot = new Robot();
server = new ServerSocket(portNumber);
System.out.println("Listening on port :****");
client = server.accept(); //loops until a client server connection is established
System.out.println("Client connected");
//Receive a message from the client
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
while(ifConnected)
{
readIn = in.readLine(); //reads the input received
if(readIn.equalsIgnoreCase("A"))
{
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
}
if(readIn.equalsIgnoreCase("B"))
{
robot.keyPress(KeyEvent.VK_B);
robot.keyRelease(KeyEvent.VK_B);
}
if(readIn.equalsIgnoreCase("C"))
{
robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);
}
if(readIn.equalsIgnoreCase("BS"))
{
robot.keyPress(KeyEvent.VK_DELETE);
robot.keyRelease(KeyEvent.VK_DELETE);
}
}
System.out.println("Unable to read user Input"); //if it can't read the input from the Client
System.exit(-1); //system exits
System.out.println("Server Ended");
System.exit(-1);
}
catch (IOException e) {
System.out.println("Can't open the Socket");
System.exit(-1);
}
catch (AWTException e) {
System.out.println("Unable to create Robot");
System.exit(-1);
}
}
}
Is there any way in which I can successfully read and send each character entered in the editText field?
If any further clarification about this is necessary let me know.
Thanks
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);
i got a little problem with my little application by using java Sockets.
if i start my Sockert-Server on pc and i'm connected withmy phone via wifi in the same network by using the (intern) network IP i can send some stuff to my server.
But if i try to send a message via the mobile internet connection,it doesn´t work..there is also no error or something else :/
Here is my android class:
public class Sockets extends Activity {
EditText textOut;
EditText ipAddress;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
ipAddress = (EditText)findViewById(R.id.ipAddress);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new DatagrammClient(ipAddress.getText().toString(),textOut.getText().toString()).execute("");
textOut.setText("");
}};
private static class DatagrammClient extends android.os.AsyncTask<String, Void, String> {
final static String LOGIN = "LOGIN";
final static String LOGOUT = "LOGOUT";
static int port = 1234;
static int length = 1024; // Länge eines Pakets
static DatagramSocket socket = null;
static InetAddress ia = null;
static DatagramPacket packet;
String hostname = "";
String msg ="";
public DatagrammClient(String hostname,String msg) {
this.hostname = hostname;
this.msg = msg;
}
/**
* Send the login package and open socket
*
* #param servername
* #throws IOException,UnknownHostEception
*/
private static void connectToServer(String servername) throws IOException,UnknownHostException{
packet = null;
byte[] ba = LOGIN.getBytes();
try {
socket = new DatagramSocket();
ia = InetAddress.getByName(servername);
packet = new DatagramPacket(ba, ba.length, ia, port);
Log.d("servername",servername);
Log.d("Internetaddress",ia.toString());
Log.d("SOCKET",socket.toString());
// sende Anmeldung
socket.send(packet);
} catch (SocketException se) {
Log.d("SocketException",se.toString());
}
catch (UnknownHostException he) {
Log.d("UnknownHost: ",he.toString());
}
catch (IOException e) {
Log.d("IOException: ",e.toString());
}
}
public static void sendMessage(String message, String hostname) throws UnknownHostException, IOException{
//if (socket == null){
DatagrammClient.connectToServer(hostname);
//}
DatagrammClient.sendMessageToServer(message);
DatagrammClient.readMessageFromServer();
//Close connection -> Send logout Package?
}
private static void readMessageFromServer(){
// Lesen der empfangenen Pakete erfolgt in eigenem Thread
LeseThread lt = new LeseThread( socket );
}
private static void sendMessageToServer(String message){
byte[] ba = null;
try {
if (!message.equals(LOGOUT)) {
// message = br.readLine();
ba = message.getBytes();
packet.setData(ba, 0, ba.length);
socket.send(packet);
Log.d("Message:",packet.toString());
} else {
ba = LOGOUT.getBytes();
packet.setData(ba, 0, ba.length);
socket.send(packet);
// Exit the system -> do we need to close the socket clientside?
//socket.close();
System.exit(0);
}
} catch (IOException e) {
System.err.println("Ausnahmefehler: " + e);
Log.d("IOEXCEPTION_MESSAGE_TO_SERVER:",e.toString());
}
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
DatagrammClient.sendMessage(msg, hostname);
}
catch(Exception e){
Log.d("Error: ",e.toString());
}
return null;
}
}
}
The permission to use the INTERNET is set in the Manifest..