How to correct the Socket Exception in emulator - android

I have written code for Client and server connectivity in android.When I run in Emulator it shows 09-16 19:04:14.783: E/ClientActivity(407): java.net.ConnectException: /10.0.2.15:8080 - Connection refused.I referred many developer.android for redirection.But it didn't work.Can anybody say the reason for this exception and how to fix this issue?
ServerActivity.java
package com.example.network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class ServerActivity extends Activity {
private TextView serverStatus;
// default ip
public static String SERVERIP = "";
// designate a port
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
serverStatus = (TextView) findViewById(R.id.textView1);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
// Toast.makeText(getApplicationContext(), i.getHostAddress.toString(),Toast.LENGTH_LONG ).show();
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
#Override
public void run() {
// do whatever you want to the front end
// this is where you can be creative
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
// gets the ip address of your phone's network
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ClientActivity.java
package com.example.network;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
serverIp = (EditText) findViewById(R.id.editText1);
connectPhones = (Button) findViewById(R.id.button1);
connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.apache.android.xmpp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:name="XMPPDemosApplication"
android:label="XMPP Demo">
<activity android:name=".XMPPClient" android:label="XMPPClient">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

You need to add redirection to work between two emulators da!
In windows, open command prompt and type-- telnet localhost 5554 (this 5554 is the port on which ur receiving emulator is running)
now u'r Telnet gets connected to this emulator. Now type this cmd : redir add tcp:src_port:dst port
the src port refers to the machine port and the dst port refers to the emulator port to which u wanna redirect. This works fine for me :)

If you are using an emulator I would suggest for you to check you firewall settings and make sure that the emulator is an exception

Also, if you're working on a laptop, and moving from one network to another, the emulator often needs to be restarted to pick up the right network settings on the new network.

Related

How to get message to send from server to Android

I have made a program to send a message from a client to a server(2 android devices), but the message is not being sent.
Here is the code of the client side application:
package com.example.clientphone;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.*;
public class MainActivity extends ActionBarActivity {
private EditText ipaddress , textfield;
private Button send;
private String ip , message;
private Socket client;
private PrintWriter printwriter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText)findViewById(R.id.editText1);
textfield = (EditText)findViewById(R.id.editText2);
send = (Button) findViewById(R.id.button1);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();// enabling strict mode and setting thread policy
StrictMode.setThreadPolicy(policy);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = textfield.getText().toString();
ip = ipaddress.getText().toString();// getting ip address
textfield.setText(" ");
try {
client = new Socket(ip, 5200);// ip address is entered over here....
printwriter = new PrintWriter(client.getOutputStream() , true);// getting the outputstream
printwriter.write(message);// writing the message
printwriter.flush();// flushing the printwriter
printwriter.close();// closing printwriter
client.close();// closing client
} catch (UnknownHostException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
});
}
}
Here is the code for server side application. I have chosen the port 5200 to connect on. I want the user to enter the IP address of the other device and not keep it hard-coded:
package com.example.serverphone;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
public class MainActivity extends ActionBarActivity {
TextView message;
private ServerSocket socket;
private Handler UpdateConversationHandler;
Thread ServerThread = null;
public static final int port = 5200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (TextView)findViewById(R.id.textView1);
UpdateConversationHandler = new Handler();
this.ServerThread = new Thread(new ServerThread());
this.ServerThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable{
#Override
public void run() {
Socket socket2 = null;
try {
socket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
while(!Thread.currentThread().isInterrupted()){
try {
socket2 = socket.accept();
BufferedReaderThread commThread = new BufferedReaderThread(socket2);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class BufferedReaderThread implements Runnable{
private Socket clientSocket;
private BufferedReader input;
public BufferedReaderThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while(!Thread.currentThread().isInterrupted()){// making sure the thread is not interrupted...
try {
String read = input.readLine();
if(read != null){
UpdateConversationHandler.post(new updateUIConversation(read));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIConversation implements Runnable{
private String msg;
public updateUIConversation(String str){
this.msg = str;
}
#Override
public void run() {
message.setText(message.getText().toString() + msg + "/n");
}
}
}
In your client you are doing network operation on the main thread. Do them in a separate thread. Do not silently supress exceptions and you will see in the log.
new Thread(new Runnable() {
public void run() {
try {
Socket client = new Socket(ip, 5200);
PrintWriter = new PrintWriter(client.getOutputStream() , true);
printwriter.write(message);// writing the message
printwriter.flush();// flushing the printwriter
printwriter.close();// closing printwriter
client.close();// closing client
} catch (Exception x) { Log.e("CLIENT", "Exception " + x); }
}).start();

Creating a messaging application (Wifi)

I'm sort of new to Android application development. I already created a very simple application that turns the device's flashlight on/off.
I'd like to try and create a messaging application where you can chat with your friends when both of you are connected to a Wifi. Sort of like "WhatsApp", "Viber", etc..
I would be really happy if you could give me guidelines and help me get the idea of how to develop such an application.
Thank you so much,
Orel.
For that you need to create server program, that will authenticate username & password and communication between diff users.., etc, and you need to send the response based on the user query.
For any network communication application consists of two components:
Server
Client
In the case of WhatsApp android app,its a client application which communicate's with the WhatsApp server.
The server with exchange the data from one client to another client, the client may be desktop, android mobile, iPhone,...etc
Generally chat programs will implemented using sockets, and its depends upon the architecture and technologies which you will chose.
Using this:
ChatServerSide
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ChatServerSide extends Activity implements View.OnClickListener {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
Button btnSendMsg;
EditText etInputMessage;
TextView tvOutputMessage;
TextView tvMyIp;
Socket socket;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_activity);
iniUi();
iniListener();
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
tvMyIp.setText("Waiting devices on " + getIpAddress());
}
private void iniUi() {
tvMyIp = (TextView) findViewById(R.id.tvMyIp);
btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
etInputMessage = (EditText) findViewById(R.id.etInputMesage);
tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
}
private void iniListener() {
btnSendMsg.setOnClickListener(this);
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onClick(View view) {
try {
String str = etInputMessage.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: " + str + "\n");
etInputMessage.setText("");
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} 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()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
String read = null;
try {
read = input.readLine();
if (read == null) {
read = "Client has leave the chat";
socket.close();
updateConversationHandler.post(new updateUIThread(read));
break;
}
updateConversationHandler.post(new updateUIThread("Client Says: " + read));
}catch(IOException e){
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
tvOutputMessage.setText(tvOutputMessage.getText().toString() + msg + "\n");
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
ChatClientSide
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClientSide extends Activity implements View.OnClickListener {
private Handler handler = new Handler();
private Socket socket;
Button btnSendMsg;
EditText etInputMessage;
TextView tvOutputMessage;
Handler updateConversationHandler;
TextView tvMyIp;
private static final int SERVERPORT = 6000;
private static String SERVER_IP = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_activity);
iniUi();
iniListener();
SERVER_IP = ActivityMain.ipToConnect;
updateConversationHandler = new Handler();
receiveMsg();
}
#Override
protected void onStop() {
super.onStop();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getServerIp(Intent intent) {
Bundle bundle = intent.getExtras();
String ip = bundle.getString("destAdress");
tvMyIp.setText("Is connected to " + ip);
return ip;
}
private void iniUi() {
tvMyIp = (TextView) findViewById(R.id.tvMyIp);
btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
etInputMessage = (EditText) findViewById(R.id.etInputMesage);
tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
}
private void iniListener() {
btnSendMsg.setOnClickListener(this);
}
#Override
public void onClick(View view) {
try {
String str = etInputMessage.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: " + str + "\n");
etInputMessage.setText("");
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void receiveMsg() {
new Thread(new Runnable() {
#Override
public void run() {
final String host = SERVER_IP;
BufferedReader in = null;
try {
socket = new Socket(host, SERVERPORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
String msg = null;
try {
msg = in.readLine();
//msgList.add(msg);
} catch (IOException e) {
e.printStackTrace();
}
if (msg == null) {
break;
} else {
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg) {
final String mssg = msg;
handler.post(new Runnable() {
#Override
public void run() {
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "Server Says: " + mssg + "\n");
}
});
}
}
chat_main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvMyIp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btnSendMsg"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="send"
android:layout_weight="0" />
<EditText
android:id="#+id/etInputMesage"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/tvOutputMessage"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TextView>
</LinearLayout>
</LinearLayout>

Android Socket Thread Add very high load at processor

I am debugging my app on my Galaxy S3 and whenever I monitor the processing .. I notice very high load the app processing . Application processing goes to 80 % sometimes which is incredibly hight
Here is the code:
package com.example.socketclient;
import android.app.Activity;
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;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
public class SocketCode extends Activity {
private boolean connected = false;
//private Handler handler = new Handler();
public TextView txt;
int doit=0;
protected SocketCore Conn;
public Button b;
public EditText TextToSend;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_code);
b = (Button)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.textView1);
TextToSend = (EditText)findViewById(R.id.editText1);
//Conn = new SocketCore(this,txt);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("ErrorButton","Button Pressed Before Toggle"+doit);
doit=1;
Log.e("ErrorButton","Button Pressed "+doit);
}
});
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
public class ClientThread implements Runnable {
Socket socket ;
String finall="",text;
PrintWriter out = null;
BufferedReader in = null;
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.0.150");
Log.d("ClientActivity", "C: Connecting...");
socket= new Socket(serverAddr,4444);
connected = true;
while (connected) {
try {
if(doit==1)
{
Log.e("ErrorButton","If");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(TextToSend.getText().toString());
finall="";
while ((text = in.readLine()) != null) {
finall += text;
Log.e("Test","Final: "+finall);
if(text=="quit")
{
socket.close();
}
Log.e("ClientActivity", "After Read "+doit+" "+finall);
break;
}
doit=0;
Log.e("ClientActivity", "Out Of IF "+doit);
runOnUiThread(new Runnable() {
public void run() {
txt.setText(finall);
}
});
}
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
txt.setText("Closed Socket");
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
public void ClientHandler(String Send)
{
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
out.println(Send);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
finall = in.readLine();
txt.setText(finall);
}
catch(IOException e)
{txt.setText("Exception");}
}
}
}
The CPU is doing that because you're running a non-stop loop that keeps feeding runnables into the UI thread, so the CPU keeps under very high load. Instead, I'd recommend that you consider using a push strategy instead of a polling strategy with something like GCM (Google Cloud Messaging), where your app wakes up when your server pushes new data onto the device. If that's not a possible solution, I'd throttle the polling rate to a lower rate and limit it to a few times per minute (or less), using Thread.sleep() periodically in run() to avoid flooding the UI thread with runnables.
Fixed
With using Thread.Sleep(200);
while (connected) {
try {
Thread.sleep(200);
Log.e("ErrorButton","If");
if(doit==1)
{

Android socket NullPointerException

I have problem with android sockets , I have two android applications Server and ServerClient , in ServerClient It gives nullPointerException on second row written below
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
I checked serverAddr is 10.0.2.2 , but then I saw that socket is null. Can anybody helps with it?
EDIT: with this serverAddress I saw that it is unreachable, maybe I must make it reachable manual ?
here is sources
*ServerClient*
package com.example.serverclient;
import android.os.Bundle;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import android.view.Menu;
public class MainActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "10.0.2.2";
private static final int REDIRECTED_SERVERPORT = 5000;
// AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
// PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
// PORT 6000
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
OutputStream sk = socket.getOutputStream();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
} catch (UnknownHostException e) {
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
tv.setText("Error3");
e.printStackTrace();
}
}
});
}
}
**Server**
package com.example.myserver;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText("Nothing from client yet");
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText(mClientMsg);
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT );
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Have you made sure that you aren't getting an UnknownHostException or a IOException? One of those has to be getting called otherwise socket would not be null.
Change (Exception e) of the error 3 para to NullPointerException and then run the client side and send a message. Error 3 will no longer be displayed on the screen and you will receive the message on Myserver.
Exception e --> NullPointerException
This class returns your response, but also needs permission of internet in manifest file.
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
mSocket = IO.socket("http://chat.socket.io");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}

How can I connect Android devices using Socket Programming?

I want to create an application for connecting multiple android devices.Here able to connect from device (Using Wifi Network) to another device(3G Network).I need to connect from device using 3G network to device using Wifi Network.How can I connect devices using 3G network to WiFi Network.
Server Side:
package com.server.org;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
public class ServerActivity extends Activity {
private TextView serverStatus;
// default ip
public static String SERVERIP = "10.0.2.15";
// designate a port
public static final int SERVERPORT = 9191;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
public void run() {
// do whatever you want to the front end
// this is where you can be creative
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
// gets the ip address of your phone's network
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client Side:
package com.client.org;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
int SERVERPORT = 9191;
Socket socket = new Socket(serverAddr,SERVERPORT );
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
Your concept is slightly on the wrong track. 3G connections mean your phones have to be connected through phone network and for that I don't think your phones will ever have static IPs. I don't even think operators today offer a static public IP to phone connections.
I would suggest you to bridge this communication via a webserver using webservices. You can implement a solution like APE and use both devices to connect to that server instead of each other.
I hope that helps

Categories

Resources