TCP from android to PC not working using java - java

I am trying to send a simple message over TCP from my android phone (using java application) to my computer. I have an socket that is listening on my computer but as soon as I run this app, it crashes. I am really new to Android developing so please bear with me...
Here is my Java code:
package com.scorekeep.clienttcp;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText textOut;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Socket socket = null;
try {
socket = new Socket("10.0.0.10",5000);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("HELLO_WORLD");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

As requested an extended example :
import android.app.*;
import android.os.*;
import android.util.*;
import java.io.*;
import java.net.*;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new connection().execute();
}
}
class connection extends AsyncTask<String,String,String> {
public static PrintWriter out;
BufferedReader in;
public static boolean running = true;
#Override
protected String doInBackground(String... message) {
try
{
InetAddress serverAddr = InetAddress.getByName("localhost");
Socket socket = new Socket(serverAddr, 8008);
// send the message to the server
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
while(running) {
String msgfromserver = in.readLine();
}
}
catch (Exception e)
{}
return null;
}
public static void sendmsg(String msg){
if(out!=null){
out.println(msg);
out.flush();
}
}
}
Usage:
Call connection.sendmsg("some text"); from OnClick method of button
And set connection.running = false; onbackpress. (Or before finishing activity)

You cannot execute background tasks like socket connection in ui thread. You should use AsyncTask.
Example
import android.app.*;
import android.os.*;
import android.util.*;
import java.io.*;
import java.net.*;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new connection().execute();
}
}
class connection extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... message) {
try
{
InetAddress serverAddr = InetAddress.getByName("ip here");
Socket socket = new Socket(serverAddr, 5000); //port here
// send the message to the server
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println("hi");
out.flush(); //optional
socket.close();
}
catch (Exception e)
{}
return null;
}
}
Note Untested. May contain errors.

Two changes in code. public static void sendmsg and public public static PrintWriter out at begining of AsyncTask class

Related

Error setting java class as object in MainActivity android studio -- cannot resolve symbol ""

I'm a beginner and I have been following several tutorials in order to parse JSON. I am just about to compile and try to run for the first time but when I tried to make an object of my java class and have the process run when the button "click" is triggered, I get an error stating " Cannot resolve symbol "fetchData" "
package com.example.h.arbitrage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click = findViewById(R.id.button);
data = findViewById(R.id.fetcheddata);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetchData process = new fetchData();
((fetchData) process).execute();
}
});
}
}
I'm also including the code for fetchData.java in case there's something in there that's causing this.
I've looked all over for the answer and it might be very obvious but I don't even have the terminology to properly research this...
import android.net.UrlQuerySanitizer;
import android.os.AsyncTask;
import com.example.h.arbitrage.MainActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data = "";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line ="";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.data);
}
}
Thanks in advance for any help.

AsyncTask - Can't connect via sockets

I am trying to establish a connection between an Android Application and a Python script via sockets.
This Java code works absolutely fantastic with my Python server.
import java.io.*;
import java.net.*;
public class client {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",5000);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
However, when I try to implement it in my Android application (see below), I have the feeling that the doInBackground() is not even called:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.DataOutputStream;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myText = (TextView) findViewById(R.id.TextView1);
Connect myConnect = new Connect();
myConnect.execute();
String myResult = Integer.toString(myConnect.getResult());
myText.setText(myResult);
}
}
class Connect extends AsyncTask<Void, Void, Integer> {
int result = 0;
#Override
protected void onPreExecute(){
result = 1;
}
#Override
protected Integer doInBackground(Void... params) {
try{
result = 2;
Socket s=new Socket("localhost",5000);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){
result = -1;
return -1;
}
result = 3;
return 3;
}
#Override
protected void onProgressUpdate(Void... values) {
}
int getResult(){
return result;
}
}
What am I missing here to make it work?
Socket s=new Socket("localhost",5000);.
That should be
Socket s=new Socket("10.0.2.2",5000);
when using an emulator.

PrintWriter giving null pointer exception

I am trying to build a multiple client single java server model. I'm doing this using threads, so I have one thread per client using AsyncTask. Thus, I am creating a client socket and the PrintWriter object in the onCreate() method using the CreateClient class and then every time the button2 is pressed, I just need to pass the question/text to the server for that particular thread. The problem is, I am getting a NullPointerException in the SendMessage class.
Here's my Client Actvity:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
//import statements for client
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
//import statements for client
import android.os.AsyncTask;
public class MainActivity extends Activity implements OnClickListener {
EditText question;
//Client sockets
private Socket client;
private PrintWriter printwriter;
private String toTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create client as soon as the activity starts
CreateClient clientConnection = new CreateClient();
clientConnection.execute();
question = (EditText)findViewById(R.id.editText1);
Button query = (Button)findViewById(R.id.button2);
query.setOnClickListener(this);
ImageButton listen = (ImageButton)findViewById(R.id.button1);
listen.setOnClickListener(this);
listen.performClick();
}
private class CreateClient extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
client = new Socket("Server IP Address", 4444);
printwriter = new PrintWriter(client.getOutputStream(), true);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
private class CloseClient extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if(printwriter != null) {
try {
printwriter.write("\n");
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
printwriter.write(toTag); // GETTING NULL POINTER EXCEPTION ON THIS LINE
printwriter.write("\n"); //delimiter
printwriter.flush();
return null;
}
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.button2:
if(validate()) //Validate is a function that validates the text
{
toTag = question.getText().toString();
//Invoke the execute method of AsynTask, which will run the doInBackground method of SendMessage Class
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
else
{
//Toast error msg
}
break;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
CloseClient closeConnection = new CloseClient();
closeConnection.execute();
}
}
Chances are that the line
printwriter = new PrintWriter(client.getOutputStream(), true);
isn't being executed in time. Try adding a println or initializing the printWriter somewhere else.
printWriter Object has not been initialized and it is still null which is causing Null Pointer Exception
printwriter.write(toTag);// at this line -->
So initialize printWriter=new PrintWriter(); before using it
Well, turns out my client socket wasn't getting created due to outdated DDMS in Eclipse. Something about DDMS not able to create a localhost connection on port 8600. So, as Tyler pointed, my printwriter = new PrintWriter(); statement wasn't getting executed. I updated DDMS and now it works just fine.

Android client is not working with server pc

I am trying to a develop a basic app for sending a string from an android client to pc server but problem is that the server is not receiving any message.I am using socket to communicate between client and server.The server is started but doesnt receving any message.
Here is the sample server code written in java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package wifi.communicate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class WIfiCommunicate
{
private static final int port=4444;
private static ServerSocket serversocket;
private static Socket clientsocket;
private static InputStreamReader reader;
private static BufferedReader breader;
private static InputStreamReader InputStreamReader;
private static String message;
public static void main(String[] args)
{
try
{
serversocket=new ServerSocket(port,0,InetAddress.getLocalHost());
System.out.println("IP: "+serversocket.getInetAddress()+ "port" +serversocket.getLocalPort());
}
catch(IOException e)
{
System.out.println("Could not listen to port: "+port);
}
System.out.println("Server started ");
while(true)
{
try
{
clientsocket=serversocket.accept();
reader=new InputStreamReader(clientsocket.getInputStream());
breader=new BufferedReader(reader);
message=breader.readLine();
}
catch(IOException e)
{
System.out.println("Message not received");
}
}
}
}
here is the android activity code
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText editText;
String n1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=(EditText)findViewById(R.id.editText1);
}
public void onClick(View view)
{
if(view.getId()==R.id.button1)
{
n1=editText.getText().toString();
new connectserver().execute(n1);
}
}
public class connectserver extends AsyncTask<String,Integer,Socket>
{
private static final String IP_address="192.168.0.101";
private static final int port=4444;
private String mText;
protected Socket doInBackground(String... params)
{
if(params.length!=1)
throw new IllegalArgumentException();
mText=params[0];
Socket client=null;
try
{
client=new Socket(IP_address,port);
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return client;
}
protected void onPostExecute(Socket client)
{
try
{
PrintWriter pwriter;
String message=mText;
editText.setText("");
pwriter=new PrintWriter(client.getOutputStream(),true);
pwriter.write(message);
pwriter.flush();
pwriter.close();
client.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

TCP/IP Connects and Sends But Doesn't Work After Initial Sends

HELP! I'm Going Crazy! I'm using a Visual Basic 6.0 Winsock for the server. I'm able to keep an active connection and I even receive from my Android App to the VB App "VER:Android,LAT:28.111921,LNG:-81.950433,ID:1038263,SND:0,VDO:0"> Which I parse and put the data in their fields.
After my initial connection I try to send a simple message from VB to the Server and I never receive it. What I do notice whenever I close my VB.NET app I recieve this in my LogCat:
11-26 15:38:16.567: I/TcpClient(986): received: null
I'm new to Android any help would be highly appreciated. I need help trying to recieve and send messages back and forth through my Client(Android) and Server(VB)
package com.WheresMySon;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class TcpClient extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new TcpClientTask().execute();
}
class TcpClientTask extends AsyncTask<Void, Void, Void> {
private static final int TCP_SERVER_PORT = 1234;
private boolean error = false;
Boolean SocketStarted = false;
protected Void doInBackground(Void... arg0) {
try {
Socket s = new Socket("10.0.2.2", TCP_SERVER_PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//send output msg
String outMsg = "VER:Android,LAT:28.111921,LNG:-81.950433,ID:1038263,SND:0,VDO:0";
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
//accept server response
String inMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpClient", "received: " + inMsg);
//close connection
} catch (UnknownHostException e) {
error = true;
e.printStackTrace();
} catch (IOException e) {
error = true;
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
if(error) {
// Something bad happened
}
else {
// Success
}
}
}
//replace runTcpClient() at onCreate with this method if you want to run tcp client as a service
private void runTcpClientAsService() {
Intent lIntent = new Intent(this.getApplicationContext(), TcpClientService.class);
this.startService(lIntent);
}
}

Categories