Client Socket problems on Android - android

package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
new Incomingdata().execute();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
private class Incomingdata extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params)
{
setMyIp(ipaddress.getText().toString());
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
while(s.isConnected())
{
String input =r.nextLine();
System.out.println(""+input);
}
in.close();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
So this is where i am, i can flush data out but can not seem to receive it back in from the server i am fairly new at this and have got help in the past from this site. I am really stuck and running out of time
Any help would be great
And Thank you

There are two different types of Socket, one is used for connecting to a host, and the other one is used to listen for connections. What you want to do is before trying to connect, make a ServerSocket that listens to incoming connections to a specific port number and wait for a new connection, as such:
ServerSocket serverSocket = new ServerSocket(2000);
Socket s = serverSocket.accept();
This should be done in your AsyncTask before trying to connect to it (accept() is blocking so it will wait for an incoming connection). So, changing the following two lines with the above and calling the AsyncTask before trying to connect to it should do the trick:
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);

Related

Simple Client Server Application android

Hello I am trying to write simple client-server application in android.Here is my code for the client.
package com.sudarshan.client;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
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
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
client = new Socket("10.0.2.2", 4444); // connect to the 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();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
Here is the code for server
package com.sudarshan.server;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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 server code crashes.It gives a error as "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sudarshan.server/com.sudarshan.server.MainActivity}: android.os.NetworkOnMainThreadException".
What am i doing wrong?
Solved.
"android.os.NetworkOnMainThreadException" means that Network related tasks are not to be done on main thread directly ie. Activity Class.So, need to make a thread under main thread then do the work.

cannot resolve symbol okhttp

i am developing a gcm chat app in android studio and i am getting this error n no idea how to resolve it. i searched about it but didn't find any thing.
Here is the code and in MainActivity.java also having same problem.
package com.example.jason.androidchat2;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.squareup.okhttp.OkHttpClient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class ChatActivity extends Activity {
EditText editText_mail_id;
EditText editText_chat_message;
ListView listView_chat_messages;
Button button_send_chat;
List<ChatObject> chat_list;
BroadcastReceiver recieve_chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
editText_mail_id= (EditText) findViewById(R.id.editText_mail_id);
editText_chat_message= (EditText) findViewById(R.id.editText_chat_message);
listView_chat_messages= (ListView) findViewById(R.id.listView_chat_messages);
button_send_chat= (Button) findViewById(R.id.button_send_chat);
button_send_chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// send chat message to server
String message=editText_chat_message.getText().toString();
showChat("sent",message);
new SendMessage().execute();
editText_chat_message.setText("");
}
});
recieve_chat=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("message");
Log.d("pavan","in local braod "+message);
showChat("recieve",message);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(recieve_chat, new IntentFilter("message_recieved"));
}
private void showChat(String type, String message){
if(chat_list==null || chat_list.size()==0){
chat_list= new ArrayList<ChatObject>();
}
chat_list.add(new ChatObject(message,type));
ChatAdabter chatAdabter=new ChatAdabter(ChatActivity.this,R.layout.chat_view,chat_list);
listView_chat_messages.setAdapter(chatAdabter);
//chatAdabter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class SendMessage extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Log.i("pavan", "url" + url);
OkHttpClient client_for_getMyFriends = new OkHttpClient();;
String response = null;
// String response=Utility.callhttpRequest(url);
try {
url = url.replace(" ", "%20");
response = callOkHttpRequest(new URL(url),
client_for_getMyFriends);
for (String subString : response.split("<script", 2)) {
response = subString;
break;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
}
}
// Http request using OkHttpClient
String callOkHttpRequest(URL url, OkHttpClient tempClient)
throws IOException {
HttpURLConnection connection = tempClient.open(url);
connection.setConnectTimeout(40000);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null)
in.close();
}
}
byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1;) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
OkHTTP is an Open Source project designed to be an efficient HTTP client.
Just add this in your build.gradle
dependencies {
compile 'com.squareup.okhttp:okhttp:2.5.0'
}
FYI
The latest release is available
implementation 'com.squareup.okhttp3:okhttp:4.9.0'

AsyncTask unfortunately stops on second execution

I'm trying to get strings from my Arduino with my Android phone, everything goes well except for when I press my updatebutton the second time, it unfortunately stops.
I can't seem to track the problem and I ran out of options so I'm asking for help to you guys now.
package com.TRY.udp2;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private String rcvStr, serverIP="192.168.0.15";
private TextView textLog;//Log for outputs
private EditText textMsg;
Button updateButton;//(dis)connect Button
Boolean connected=false;//stores the connectionstatus
DataOutputStream dataOutputStream = null;//outputstream to send commands
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button updateButton = (Button) findViewById(R.id.updateButton);
textMsg = (EditText) findViewById(R.id.textMsg);
textLog = (TextView) findViewById(R.id.textLog);
updateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String textlogMsg = textMsg.getText().toString();
new synchTask().execute(textlogMsg);
}
});
}
private class synchTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String msg=params[0].toString();
InetAddress toAddress = null;
try
{
toAddress = InetAddress.getByName(serverIP);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
int port=5000;
DatagramSocket dtSocket = null;
try
{
dtSocket = new DatagramSocket(port);
}
catch (SocketException e1)
{
e1.printStackTrace();
}
byte[] dataBytes = msg.getBytes();
DatagramPacket sndPacket = new DatagramPacket(dataBytes, dataBytes.length, toAddress, port);
try
{
dtSocket.send(sndPacket);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
byte[] rcvData = new byte[1024];
DatagramPacket rcvPacket = new DatagramPacket(rcvData, rcvData.length);
dtSocket.receive(rcvPacket);
rcvStr = new String(rcvPacket.getData());
}
catch (IOException e)
{
e.printStackTrace();
}
return rcvStr;
}
protected void onPostExecute(String result) {
textLog.setText(rcvStr);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and if there's a better way of getting strings from arduino please help out.
You probably need to close dtSocket at the end of doInBackground(). Otherwise you will try to create a socket on a bound port when you execute it the second time.

Trying to make my android application put files on my ftp server

I have spent a lot of time trying to make this code work, and in its current state it almost exactly mirrors the code I found at https://stackoverflow.com/questions/3482583/apache-ftpclient-failing-to-download-larger-files. I am also using apache commons net.
for some reason my application never gets past the client.connect step, even when i plug in other IP addresses of ftp servers that should work.
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
public class FtpClientService extends Activity {
//static int fail;
public FtpClientService(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.ftp);
FtpConnect();
}
public static void FtpConnect(){
String userName="usrname";
String passWord = "password";
String ftpAddress = "127.0.0.1"; //this isnt the ip address I was using...
String retrieveFromFTPFolder = "/Pictures/";
String strLine;
DataInputStream inputStream = null;
BufferedReader bufferedReader = null;
FTPClient client = null;
FTPFile[] ftpFiles = null;
int reply;
try{
client = new FTPClient();
client.setListHiddenFiles(true);
client.connect(ftpAddress); //this right here is where it fails
client.login(userName, passWord);
client.setFileType(FTP.BINARY_FILE_TYPE);
if(!client.completePendingCommand()) {
client.logout();
client.disconnect();
System.err.println("File transfer failed.");
}
} catch (Exception e) {
if (client.isConnected()) {
try {
client.logout();
client.disconnect();
}
catch (IOException f) {}
}
}
finally{
if (client.isConnected()) {
try {
client.logout();
client.disconnect();
}
catch (IOException f){}
}
}
}
public static void main(String[] args) {
FtpConnect();
}
Thanks in advance!
In the connect method, pass it a constructed InetAddress with appropriate address and port.
Also, don't perform FTP connection on main thread, consider using AsyncTask.
Try using this:
client.connect(InetAddress.getByAddress(ftpAddress,new byte[]{127,0,0,1}));

To shorten the URL using google api

Hi i am using an example to make a url shorten. But cant able to do that, here's my code
package com.tinyurl;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.util.GenericData;
public class tinyurl extends Activity implements OnClickListener {
EditText original;
TextView txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.Button01);
original = (EditText) findViewById(R.id.edittext);
txt = (TextView) findViewById(R.id.TextView03);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAau1E_WrYwMiTNqhK5hgH0tyWudyahbOI";
String tinyUrl = null;
String original = "http://www.google.com/";
HttpTransport transport = GoogleTransport.create();
GoogleHeaders defaultHeaders = new GoogleHeaders();
transport.defaultHeaders = defaultHeaders;
transport.defaultHeaders.put("Content-Type", "application/json");
transport.addParser(new JsonHttpParser());
HttpRequest request = transport.buildPostRequest();
request.setUrl(GOOGL_URL);
GenericData data = new GenericData();
// data.put("longUrl", "http://www.google.com/");
data.put("longUrl", original);
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;
HttpResponse response = null;
try {
response = request.execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("eception occured", e.toString());
}
Result result = null;
try {
result = response.parseAs(Result.class);
Log.d("TinyUrl", result.shortUrl.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class Result extends GenericJson {
public String shortUrl;
}
}
but the thing is i am getting in Log is java.net.UnknownHostException:www.googleapis.com
You have to modify AndroidManifest.xml to grant permission of "android.permission.INTERNET"
Info from: http://android-er.blogspot.com/2011/09/query-and-parse-google-json.html
This looks a network issue. Use the code given here to access a website using java network api http://www.coderanch.com/t/440335/sockets/java/Access-website-Java-Code
This will allow you to track the actual error and once that is fixed you can use any JSON lib to parse the response from server.
Ah, if you're getting UnknownHostException that means your DNS server is not successfully resolving www.googleapis.com. I'd check to make sure that you actually have a working network connection.

Categories

Resources