Android Client, Pc Server Socket d'ont work over 3g - android

I try to create a client server socket beetwen my droid(client) and my PC(server), when i am in local(over wifi) it work perfectely, but when il try over 3G i get this exception when the server try to get clientsocket.getOutputStream()
at java.lang.Thread.run(Unknown Source)
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
What's the probleme, do eny one know the solution of this?
help please :-(
The Server
public class Server {
ServerSocket serverSocket;
public LinkedBlockingQueue<CDRecCourseDisplay> recCours;
public LinkedList<ClientMail> clientMails;
static Server server;
public static Server getInstance(){
if(server == null){
server = new Server();
}
return server;
}
Server() {
// TODO Auto-generated constructor stub
try {
serverSocket = new ServerSocket(54444);
recCours = new LinkedBlockingQueue<CDRecCourseDisplay>(10);
clientMails = new LinkedList<ClientMail>();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.start();
}
private void start(){
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true){
try {
Socket socket = serverSocket.accept();
new Thread(new Client(socket)).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
class Client implements Runnable{
Socket socket;
DataInputStream in;
DataOutputStream out;
public Client(Socket socket) {
// TODO Auto-generated constructor stub
this.socket = socket;
if(socket == null) return;
try {
InputStream i = socket.getInputStream();
OutputStream o = socket.getOutputStream();
in = new DataInputStream(i);
out = new DataOutputStream(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
out.writeUTF("Test Message");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
String buf = in.readUTF();
Log.d("MESSAGE", buf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
}
and the client
class Client implements Runnable{
Socket socket;
DataInputStream in;
DataOutputStream out;
public void run() {
// TODO Auto-generated method stub
boolean conected = false;
while(!conected){
try {
Thread.sleep(500);
socket = new Socket("213.233.216.25", 54444);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
conected = true;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
}
}
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
while(true){
try {
String buf = in.readUTF();
log.d("MESSAGE", buf);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
while(true){
try {
out.writeUTF("Test message from the phone");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}

Most networks (Wifi and 3G) use NAT. NAT allows outbound connections, but prevents inbound (internet to device) connections.
When your server and device are both on the same network, as in your case, then this works as you are not traversing NAT gateway.
Rationale: what you are trying to do (connecting from internet to device) will not work in most networks.

Related

Connect/disconnect operations inside another thread

I defined connection variable in top of the main class:
private XMPPConnection connection;
I am connecting to server with following code:
public void connect(final String username,final String password) {
Thread t=new Thread(new Runnable() {
#Override
public void run() {
ConnectionConfiguration connConfig=new ConnectionConfiguration("server ip", 5222,"localhost");
XMPPConnection connection=new XMPPTCPConnection(connConfig);
try{
connection.connect();
}catch(XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username,password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setConnection(connection);
}
});
t.start();
}
You see I am using thread for this operation.And if connection was successful setConnection method is calling.
setConnection method:
public void setConnection(XMPPConnection connection) {
this.connection=connection;
if (connection != null) {
//Other stuff
....
So,I am setting connection variable inside thread.But when I want to disconnect from server i am getting crash report.
Disconnect code:
try{
connection.disconnect();
}catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Report:
01-27 14:14:05.162: E/XMPPConnection(3160): Error in listener while closing connection
01-27 14:14:05.162: E/XMPPConnection(3160): android.os.NetworkOnMainThreadException
01-27 14:14:05.162: E/XMPPConnection(3160): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
01-27 14:14:05.162: E/XMPPConnection(3160): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-27 14:14:05.162: E/XMPPConnection(3160): at java.net.InetAddress.getLocalHost(InetAddress.java:365)
01-27 14:14:05.162: E/XMPPConnection(3160): at org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy.<init>(Socks5Proxy.java:108)
I know this error.Android doesn't allow to use network operations from ui thread.But I already set connection inside another thread.Why do i need one more thread for disconnect operation ?
I followed this tutorial:http://developer.samsung.com/technical-doc/view.do?v=T000000119
And in this tutorial they didn't use another thread for disconnect.Why I am getting this error ?
Using you code which you have posted. define strict mode thread policy permission in onCreate method of Activity or Application
Assuming you have given INTERNET permission in manifest
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
If you dont wants to use the code which you have posted thn alternate solutions for that below i hve mentioned
Use Async task for the Network related operation or long process related
public class MyActivity extends Activity {
XMPPConnection connection;
private String username;
private String password;
public void connect(final String username, final String password) {
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"server ip", 5222, "localhost");
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
} catch (XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username, password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class XMPPConnection extends AsyncTask<Void, Void, Void> {
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(Void... params) {
connect(username, password);
return null;
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// from here update the ui and make ui related changes once
// onpostExecute is called
setConnection(connection);
}
}
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.test_layout);
username = "username#chat.abc.com";
password = "1234567";
new XMPPConnection().execute();
}
}
also Please check this
For async and ui changes , network related operation on main thread related please check this
and make sure setConnection(XMPPConnection connection) you are not doing any UI update related things..
OR you can also try
XMPPTCPConnection connection;
#Override
protected void onResume() {
super.onResume();
connect(LOGGED_USERNAME,"pass");
}
#Override
public void onPause() {
super.onPause();
try{
connection.disconnect();
}catch (SmackException e) {
e.printStackTrace();
}
}
private Handler handler = new Handler() {
/* (non-Javadoc)
* #see android.os.Handler#handleMessage(android.os.Message)
*/
#Override
public void handleMessage(Message msg) {
setConnection(connection);
}
};
public void connect(final String username, final String password) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"server ip", 5222, "localhost");
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
} catch (XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username, password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendEmptyMessageAtTime(0, 1000);
}
});
t.start();
}
public void setConnection(XMPPTCPConnection connection) {
this.connection=connection;
if (connection != null) {
....

Android Software caused connection abort and Async task

I use a bluetooth_access Async task to establish a connection and I need continue to use the input stream and out stream of the bluetooth socket I established.
The issue I having is when I clicked button1 or button2, it sometimes (not all the times) cause Software caused connection abort. It got tripped on out.write(bytes) when clicked.
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)this.findViewById(R.id.button1);
button2 = (Button)this.findViewById(R.id.button2);
button3 = (Button)this.findViewById(R.id.button3);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
try {
for (int i = 0; i < 3; i++) {
test();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean connected = false;
private BluetoothSocket sock;
private InputStream in;
private OutputStream out;
private Button button1;
private Button button2;
private Button button3;
private TextView data_t;
private BufferedReader in_read;
public void test() throws Exception {
if (connected) {
return;
}
new bluetooth_access().execute("");
}
#Override
public void onClick(View v){
// TODO Auto-generated method stub
if(v.equals(button1)){
String s = "turn left";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(v.equals(button2)){
String s = "turn right";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//new post_data().execute("");
}
if(v.equals(button3)){
String s = "read ADC";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class bluetooth_access extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
BluetoothDevice Pi = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice("00:15:83:0C:BF:EB");
Method m=null;
try {
m = Pi.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sock = (BluetoothSocket)m.invoke(Pi, Integer.valueOf(1));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sock.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("PiTest", "++++ Connected");
return null;
}
#Override
protected void onPostExecute(String result) {
;
TextView text = (TextView) findViewById(R.id.textView5);
text.setText("Connected through Bluetooth");
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
// original
try {
in = sock.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out=sock.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
You are trying to write to a socket stream from your main UI thread (from onClick), i would consider doing all socket communication from asynctask itself, or another thread if needed.
your connected variable is not being set, not sure if that was intentional, it can cause multiple execution of your bluetooth asynctask.

Android: Socket is closed

PCClient :
public class PCServer
{
/**
* #param args
*/
static Socket socket = null;
private static String ip = "192.168.42.129";
private static int port = 18181;
public static void main(String[] args)
{
// TODO Auto-generated method stub
try
{
socket = new Socket(ip, port);
} catch (UnknownHostException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
SendMsg(ip, port, "BZT");
GetMessage getMessage = new GetMessage();
getMessage.start();
} catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void SendMsg(String ip, int port, String msg) throws UnknownHostException, IOException
{
try
{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write(msg);
writer.flush();
writer.close();
//socket.close();
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
static class GetMessage extends Thread
{
#Override
public void run()
{
// TODO Auto-generated method stub
super.run();
try
{
while (true)
{
System.out.println("--------------------------------------------------------");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
System.out.println(str);
//client.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
AndroidServer : Service
public class SocketService extends Service
{
public static final int SERVERPORT = 18181;
ServerSocket serverSocket;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO Auto-generated method stub
try
{
serverSocket = new ServerSocket(SERVERPORT);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
GetSocketMessage getSocketMessage = new GetSocketMessage();
getSocketMessage.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
try
{
this.serverSocket.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class GetSocketMessage extends Thread
{
#Override
public void run()
{
// TODO Auto-generated method stub
super.run();
try
{
Log.i("s", "S: Connecting...");
while (true)
{
Socket client = serverSocket.accept();
Log.i("s", "S: Receiving...");
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
Log.i("s", "S: Received: '" + str + "'");
if ("BZT".equals(str))
{
Intent intent = new Intent("com.StarHope.ZWGKXT.connected");
sendBroadcast(intent);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write("OK");
writer.flush();
writer.close();
}
if ( Lbjy_usbActivity.content !=null )
{
Log.i("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "oooooooooooooooooooooooooooooo");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write("");
writer.flush();
writer.close();
}
}
catch (Exception e)
{
Log.i("s", "S: Error");
e.printStackTrace();
}
finally
{
Log.i("s", "S: Done");
}
}
}
catch (Exception e)
{
Log.i("s", "S: Error");
e.printStackTrace();
}
}
}
}
The android phone server can received the message sent from PCClient "BZT",
But when the phone send "OK" to PC , there is always an
Exception:java.net.SocketException: Socket is closed.
How can I fix this?
Closing any stream obtained using getOutputStream() or getInputStream() closes the socket.
Do you receive something before 'BZT' ? If so, the socket will be closed after you sent the empty answer.
You should use only one output stream, and flush() each message without closing.

Android Socket communication Exception

My server code
public class RemoteServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF().toUpperCase());
dataOutputStream.writeUTF("sajol");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
My client code for android device
public class Client extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Button b = findViewById(R.id.b)
textOut = (EditText) findViewById(R.id.t);
Button buttonSend = (Button) findViewById(R.id.b);
textIn = (TextView) findViewById(R.id.te);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Thread t = new Thread(r);
t.start();
}
};
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.239", 8888);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("Sajol", e+"");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Sajol", e+"");
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Sajol", e+"");
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Sajol", e+"");
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Sajol", e+"");
}
}
}
}
};
}
when i run this client code on emulator server response .But when i run client code on real device server program does not response.I found the ip address using in my code by execute ipconfig command on cmd. My pc(windows 7) and android device both are connected to wifi.
i got following exception
java.net.SocketTimeoutException: Connection timed out
Please give me solution

How to separate my code to many method?

I am a new in android developing, I've code to connect to server and send commands,
How to separate connection code in method and sending code in another method.
my code as following:
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
// connect code
socket = new Socket("172.16.149.64", 8888);
// sending code
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Write a class of your own and make the Socket one of its member variables. You can then write connect() and sendData() methods to your class using the same socket in both methods.

Categories

Resources