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.
Related
I am trying to make a socket setup in java.
And i want to send and receive data from client to server.
Client is my android Application and server is my PC.
Client to Server is getting connected and also receiving the data. But when i am trying to send it from the server to client, the android device is not receiving it. I am trying to mention it in a textview or as a Toast.
Thanks in advance
Android Studio 3.1- android version is oreo
Socket Test V 3.0.0
CLIENT:(works fine)
public class SendMessage extends AsyncTask<String, Void, Void>
{
Socket s;
DataOutputStream dos;
PrintWriter pw;
#Override
protected Void doInBackground(String... voids)
{
String message = voids[0];
try
{
s = new Socket( "197.70.107.35", 3344 );
pw = new PrintWriter( s.getOutputStream() );
pw.write( message );
pw.flush();
//pw.close();
//s.close();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
SERVER PART (Issue)
public class MainActivity extends AppCompatActivity {
EditText e1;
TextView e2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
e1 = (EditText) findViewById( R.id.editText );
e2 = (TextView) findViewById( R.id.receive );
Thread myThread = new Thread( new MyServerThread() );
myThread.start();
}
class MyServerThread implements Runnable {
Socket s;
ServerSocket ss;
InputStreamReader inr;
BufferedReader bufferedReader;
String message;
Handler h = new Handler();
public void run() {
try {
char[] data = new char[10];
ss = new ServerSocket( 3344 );
while (true) {
InputStreamReader inr = new InputStreamReader( s.getInputStream() );
int da = inr.read( data, 0, 9 );
System.out.print( data );
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void send(View v)
{
SendMessage SendMessage= new SendMessage();
SendMessage.execute( e1.getText().toString());
}
}
Need to receive data from the SERVER to the mobile application(client) as a Toast msg or in a Textview.
I have an android client that is receiving/sending data with a python server. I was able to correctly send and receive data to the server using dos.writeUTF() and dis.readUTF(). However writeUTF() was giving me problems server side because I didn't need the first to 2 bytes that it writes and so I have problems parsing the data correctly. So I opted to use dos.write(b, int, b.length) instead and it worked great server side. But I am not sure how to handle the input stream now.
Here is the android client:
public class ExecuteCommand extends Activity implements View.OnClickListener {
EditText message;
TextView message_received;
Button send_button;
String serverResponse="";
String ip="192.168.1.110";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_execute_command);
message = (EditText)findViewById(R.id.editText1);
message_received=(TextView) findViewById(R.id.server_output);
send_button = (Button)findViewById(R.id.button1);
send_button.setOnClickListener(this);
}
public void onClick(View arg0) {
Thread t = new Thread(){
#Override
public void run() {
try {
Socket s = new Socket(ip, 9999);
OutputStreamWriter osw= new OutputStreamWriter(s.getOutputStream(), "UTF-8");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
byte[] bufO=message.getText().toString().getBytes("UTF-8");
dos.write(bufO,0,bufO.length);
dos.flush();
dos.close();
DataInputStream dis = new DataInputStream(s.getInputStream());
byte[] bufI= new byte[1024];
int bytesread= dis.read(bufI);
serverResponse= String.valueOf(bytesread);
dis.close();
s.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
if(message.getText().toString().equals("")){
Toast.makeText(this, "Empty command", Toast.LENGTH_SHORT).show();
}
else{
t.start();
Toast.makeText(this, "Command sent", Toast.LENGTH_SHORT).show();
message_received.append("Server Output: "+serverResponse + "\n");
}
}
}
Here is the Python server:
import socketserver
import socket
class MyHandler(socketserver.BaseRequestHandler):
def handle(self):
self.sentence= self.request.recv(1024).strip()
self.num=len(self.sentence)
print(self.sentence.decode('utf-8'))
self.request.sendall(self.sentence.encode('utf-8'))
def main():
print ("Opening socket")
host='192.168.1.110'
port=9999
server1=socketserver.TCPServer((host,port),MyHandler)
print ("Running server")
server1.serve_forever()
main()
you may do something like this-
BufferedReader reader=new BufferedReader(new InputStreamReader(s.getInputStream()));
String response=reader.readLine();
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 am working on a chat application. Currently i did like that when i open the ChatActvity, all sockets are registered and the chatting works... Now i want to change the coding structure.. I want to open the sockets in a class, not in Activity class and i need to add a listener to that class. How i implement this..?
private class Chatroom {
private static void initialise() {
// Initialising the sockets and registering listeners to each socket
}
}
I want to notify in my activity class when the socket listeners in the Chatroom class get called..
here is probably what you need :
public class RequestSender extends AsyncTask<String, Void, String> {
private final static String serverIP = "192.168.1.1";
private final static Integer serverPort = 1234;
private ServerResponseListener listener = null;
public void setServerResponseListener(ServerResponseListener listener){
this.listener=listener;
}
public interface ServerResponseListener {
public void onResponseReceive(String response);
}
#Override
protected String doInBackground(String... params) {
Socket socket = null;
try {
socket = new Socket(serverIP, serverPort);
} catch (IOException e) {
// return "server is unreachable" message or something
}
PrintWriter requestWriter = new PrintWriter(socket.getOutputStream());
BufferedReader resultReader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String request = params[0] //for example
requestWriter.println(request);
requestWriter.flush();
String result = null;
while ((result = resultReader.readLine()) != null) {}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
listener.onResponseReceive(result);
}
}
here is example how to execute AsynchTask from Activity :
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestSender requestSender = new RequestSender();
requestSender.setServerResponseListener(new RequestSender.ServerResponseListener(){
#override
public void onResponseReceive(String response){
//
}
});
requestSender.execute("message");
}
}
read this : http://developer.android.com/reference/android/os/AsyncTask.html
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);