I have setup a Java server on my computer and a client on my Android phone.
However when I launch the app and go to the activity that deals with the client, it restarts the app back to the first activity. This happens when the client method is being executed.
The client code is this
public class ServerInterface extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String message = "test1";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_interface);
sendCommand("test");
}
public void sendCommand(String command) {
try {
client = new Socket("192.168.100.50", 43596); //Connect to PC server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(command);
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I don't know what's going wrong here.
Thanks.
You have to run the networking in a async thread. Android does not allow it on the main thread(place inside the class you are to use it in)
private class Connect extends AsyncTask<String, Integer, Boolean> {
protected Boolean doInBackground(String... urls) {
try {
client = new Socket("192.168.100.50", 43596); //Connect to PC server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(command);
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
Then to do the networking:
new Connect().execute("nullable unless used for dynamic links");
Related
I'm newer programer in android .. I need help
to sending text between two phone by wifi
first : server
second :client
I'm searching more but i need Simple code and easy to help me
thnx for advance
I guess sockets is what you are looking for...
To create a socket in android the socket must be created in a thread.
Client side example:
private final String IP = "9.9.9.9";
private final int PORT = 8080;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new MainThread()).start();
}
class MainThread implements Runnable {
#Override
public void run() {
try {
InetAddress address = InetAddress.getByName(IP);
socket = new Socket(address,PORT);
new Thread(new GetThread()).start();
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class GetThread implements Runnable {
#Override
public void run() {
try {
InputStreamReader isR=new InputStreamReader(socket.getInputStream());
BufferedReader bfr=new BufferedReader(isR);
while(true) {
String textMessage = bfr.readLine();
// TODO: Insert logic which use the recived message (textMessage)
}
}
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
In the thread, the socket is waiting for data to be sent (while(true)).
and the IP is the ip of the server (if you are connecting to your computer
with wifi, you should check your ip address with ipconfig in the command line).
I am trying to create an Android Server and Client on C# base on TCP Socket. I want them both to send and received a string(Data) so I can make a command base on the given string(Data). For the meantime, the Server can listen to incoming clients and the Clients can connect to Server. But I have two problem and i can't solve it.
PROBLEMS:
1. When i try to send the data to Server, the Server was unable to Read it.
2. When the Client is Disconnected, the Server is giving me a loop of Null.
I already try to Search about communicating C# and Android using TCP but i didn't found anything like what i need.
The following code is for Android Server.
I am having a loop of Null in class CommunicationThread when the client is Disconnected. I think it's because I am using a while for reading the Data from client, but since it become disconnected then it is resulting a null.
public class MainActivity extends AppCompatActivity {
TextView tx1, tx_waiting;
private ServerSocket serverSocket;
Handler updateConversationHandler, dg;
Thread serverThread = null;
public static final int SERVERPORT = 6000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tx1 = (TextView)findViewById(R.id.textView1);
tx_waiting = (TextView)findViewById(R.id.tx_waiting);
//Start the Server
try{
updateConversationHandler = new Handler();
dg = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
tx_waiting.setVisibility(View.VISIBLE);
Log.d("Server Starting","Server Already Started.");
}catch (Exception e){
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
Log.d("Server Stop","Successfully Stopped the Server Without any Error.");
} catch (IOException e) {
Log.e("Server Failed to Stop",e.toString());
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
Log.d("Server Thread","Server Thread Already Started.");
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
Log.d("Server Socket","New Client is Connected");
} 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()));
Log.d("Input Stream","Input Stream Received!.");
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
Log.d("Update Convers.","Conversation was Updating...");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
Log.d("Client Data",msg.toString());
}
}
}
The following code is for C# Client to Connect and Send the Data.
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
Task f = Task.Factory.StartNew(() => {
//Connect the Client into Server
try {
clientSocket.Connect(tb_ip.Text, int.Parse(tb_port.Text));
}
catch (Exception ezz) {
MessageBox.Show("Server Not Found.");
}
//Assuming that the CLient is Connected then Send a Sample Data
try {
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes("This is Sample Data");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
catch (Exception er) {
Console.WriteLine(er.ToString());
}
});
I have no method yet for Sending the Data from Server to Client since I am just starting to make this thing works, But if you have anything that can help me about this then i will really appreciate it. Thanks.
I'm trying to send a single string from android to pc and after a bit of research on this site and others I've found out about sockets and how to use them. I have written the server program that can receive strings sent to it. Below is the code.
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 9021;
public static void main(String [] args) throws IOException, ClassNotFoundException{
server = new ServerSocket(port);
while(true){
System.out.println("Waiting for client request." + InetAddress.getLocalHost());
Socket socket = server.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String)ois.readObject();
System.out.println("Message received: " + message);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Hi Client: " + message);
ois.close();
oos.close();
socket.close();
if(message.equalsIgnoreCase("exit")){
break;
}
}
System.out.println("Shutting down serve");
server.close();
}
I have tested this using a pc client program that sends string and have confirmed that this server script works. I am trying to now implement the same concept in android but facing a lot of trouble mostly due to the fact that the tutorials online for this task is very outdated (2-3 years) so nothing works as expected. Can anyone tell me how to write a very simple android app in which a single string is sent over socket?
From what I can see in the logcat, the outdated tutorials on the internet are not working because android has apparently introduced in recent versions a very aggressive process manager which monitors the behaviour of threads and if there is any repeated thread actions, it shuts it down without notice.
Edit: As per a solution I have implemented an asynctask. But now the server is not receiving and says Address already in use. I think it is because of socket address in my android code. Please help!
public class MainActivity extends Activity {
private Button button;
private EditText message;
private TextView finalResult;
//InetAddress host;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (EditText) findViewById(R.id.et_time);
button = (Button) findViewById(R.id.btn_do_it);
finalResult = (TextView) findViewById(R.id.tv_result);
/*
try {
host = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String msg = message.getText().toString();
runner.execute(msg);
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
int clientport = 8080;
String resp;
#Override
protected String doInBackground(String... params) {
publishProgress("Sending...");
String msg = params[0];
for(int i=0;i<=5;i++){
//establish socket connection to server
try {
socket = new Socket( "100.69.73.16",clientport);
//write to socket using Objectouputstream
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(msg+i);
oos.close();
socket.close();
Thread.sleep(100);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp = "Message has been sent";
return resp;
}
#Override
protected void onPostExecute(String result) {
finalResult.setText(result);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... values) {
finalResult.setText(values[0]);
}
}
}
Ok so I solved the problem of 'address already used' by changing port number. Apparently the port number was being used by other programs on my laptop. So in retrospect for anyone checking on how to do this, you can use my above code and remember to change the port number in both codes to something similar. Also in my android code where the socket is opened, you can put in the local ip address (very important, google gives you external) for your computer.
That is my program in java for my android app. I tried to create tcp connection with tcp server. I can connect to server with another applications so that i can send and receive from tcp server. With my code and with my program i can send messages to server very eazy, but i have troubles with receiving messages from server.
private Socket socket;
private final int SERVERPORT = 6060;
private final String SERVER_IP = "192.168.0.8";
public TextView tv;
private PrintWriter out;
private InputStream in;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)this.findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
}
Here is my problem i dont know how to receive strings or bytes from server. When i run my app on phone it closes the open window and say that program stop working. If i delete this section of code(public void ONCLICK2) i can transmit messages to server.
public void ONCLICK2(View view) {
try {
in=socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte array[]=new byte[1];
try {
int i=in.read(array);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So please help me with that section of code. How can i receive string send from TCP server.
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
out.println(str);
out.flush();
}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);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Simply put, the problem is you are intercepting the byte array of an unknown length and attempting to store them in array the size of one. Furthermore, it is ideal to append the packet size prior to the data in the packet and perhaps create the intercept in a separate thread waiting for incoming packets.
To just fix your ONCLICK2 you should do the following:
byte[] data = new byte[6556];
try {
in = socket.getInputStream();
// NOTE: The data byte array will contain empty values if
// under the size of 6556
int size = in.read(data);
// send to LogCat
Log.e("String", data.toString());
} catch (Exception e) {
e.printStackTrace();
}
I have not tested this code, but this should fix your problem.
I want to transfer data from Android device to the java desktop server. I have a text and button. As I press the button on the device, the text should be displayed on the java desktop server. I also have added AsyncTask in the client. The error code has also been added. The port i have used is 4444 and the ip address I used is of my local host address.
I am doing a very silly mistake. Can you please guide me.
I run the server code, it first gives me : Server started. Listening to the port 4444.
Now, I run the client code and write something on my mobile. As I press my button, it gives me error. And the app crashes and closes. I am a new one. Thanks in advance.
Client Code :
public class MainActivity extends Activity {
#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", 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();
}
}
});
}
public class Asynctask extends AsyncTask<View, Integer, Socket>
{
private static final String IP_ADDRESS = "134.190.162.165"; // Toshiba laptop
// private static final String IP_ADDRESS = "10.0.0.2"; // Toshiba laptop
private static final int DEST_PORT = 4444;
private EditText mTextField;
/**
* Store provided views (used later in onPostExecute(...)).
*
* Create socket to communicate with server (blocking call).
*/
protected Socket doInBackground(View... params)
{
// Store provided views.
if (params.length != 1)
throw new IllegalArgumentException();
mTextField = (EditText) params[0];
// Create socket.
Socket client = null;
try
{
client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return client;
}
/**
* Write to server.
*/
protected void onPostExecute(Socket client)
{
try
{
PrintWriter printwriter;
String messsage;
messsage = mTextField.getText().toString(); // get the text message on the text field
mTextField.setText(""); // Reset the text field to blank
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Server Code:
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 error which I get is:
FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
libcore.io.IoBridge.connectErrno(IoBridge.java:127)
libcore.io.IoBridge.connect(IoBridge.java:112)
java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
java.net.Socket.startupSocket(Socket.java:572)
java.net.Socket.tryAllAddresses(Socket.java:127)
java.net.Socket.<init>(Socket.java:177)
java.net.Socket.<init>(Socket.java:149)
com.example.client.MainActivity$1.onClick(MainActivity.java:42)
android.view.View.performClick(View.java:3567)
In the manifest file, I have added all the requirements. It does not give any compile time error.
I checked from many websites but the code which is working is this only. But I dont know where I am making mistake in running it or somewhere else.
If any other option is there, please suggest me, i am scratching my head since long
Thanks
Your code seems very confusing. The client seems to have code for doing the network connection and I/O both on the main thread (in the OnClickListener attached to button) and in the AsyncTask (which is never created). Try this for an OnClickListener:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
message = textField.getText().toString(); //get the text message on the text field
textField.setText(""); //Reset the text field to blank
new Asynctask().execute(message);
}
});
But you have another problem: while your AsyncTask is (correctly) making the socket connection in doInBackground, it is incorrectly doing the network I/O in onPostExecute. The network I/O also needs to be done in the background. Try this for an AsyncTask:
public class Asynctask extends AsyncTask<String, Void, Void> {
private static final String IP_ADDRESS = "134.190.162.165"; // Toshiba laptop
// private static final String IP_ADDRESS = "10.0.0.2"; // Toshiba laptop
private static final int DEST_PORT = 4444;
private EditText mTextField;
/**
* Store provided views (used later in onPostExecute(...)).
*
* Create socket to communicate with server (blocking call).
*/
protected Void doInBackground(String... messages) {
if (messages.length != 1) { return null; }
String message = messages[0];
// Create socket.
Socket client = null;
try {
client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Write to server.
try {
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The above is entirely untested, so it may not be exactly right. I also didn't look at your server code; this answer just addresses the NetworkOnMainThreadException problem.