Android: Socket is closed - android

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.

Related

Android : How to Send a string over wi-fi without using printwriter?

The program here shows passing a string using wi-fi. I need a solution which does not require print writer or a simple solution which helps me send two different strings while toggling the buttons
switch3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (switch3.isChecked()) {
messsage = "S";
Log.d("On", "Button On" + messsage);
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
// client = new
// Socket(etIP.getText().toString(), port);
client = new Socket("192.168.4.1", 100);
printwriter = new PrintWriter(client
.getOutputStream(), true);
printwriter.write(messsage);
printwriter.flush();
//printwriter.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} else {
messsage = "T";
Log.d("off", "Button off " + messsage);// etMsg.getText().toString();
// etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
// client = new
// Socket(etIP.getText().toString(), port);
//client = new Socket("192.168.4.1", 100);
printwriter = new PrintWriter(client
.getOutputStream(), true);
printwriter.write(messsage);
printwriter.flush();
//printwriter.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
}
});
You can send data by this way ->
try {
Socket socket = new Socket(DESTINATION_ADDRESS, DESTINATION_PORT);
// Exmp : Socket socket = new Socket("192.168.0.101", 80);
OutputStream outToServer = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(SEND_STRING);
// Exmp : out.writeUTF("TEST");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}

UnknownHostException causes Fatal error in AsyncTask

I have the following code, and all works fine when I can connect to the server:
public void getXMLData()
{
if (skipUpdate)
{
skipUpdate=false;
return;
}
skipUpdate=true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int SERVERPORT=0;
try {
SERVERPORT = Integer.parseInt(prefs.getString("pref_key_port_1","Port"));
} catch (NumberFormatException e) {
txtStatus.setText("Invalid Port Number");
return;
}
String SERVERHOST = prefs.getString("pref_key_host_1","127.0.0.1");
String PASSWORD = prefs.getString("pref_key_pass_1", "password");
try {
XMLFetcherTask myXMLFetcherTask = new XMLFetcherTask(SERVERHOST,SERVERPORT,PASSWORD);
myXMLFetcherTask.execute();
} catch (Exception e) {
txtStatus.setText("Error "+e.getMessage());
return;
}
skipUpdate=false;
}
public class XMLFetcherTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String password="";
XMLFetcherTask(String addr, int port, String pass){
dstAddress = addr;
dstPort = port;
password=pass;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(password);
response="";
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (response.toLowerCase().indexOf("</response>")<0)
{
response+=input.readLine();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("UnknownHostException: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("IOException: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("Exception: " + e.getMessage());
} finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//txtStatus.setText("Exception Finally: " + e.getMessage());
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if( !(response.substring(0,5).equalsIgnoreCase("<resp") || response.substring(0,5).equalsIgnoreCase("<?xml")) ) //!response.substring(0,5).equalsIgnoreCase("<?xml") ||
{
txtStatus.setText("Server response doesn't look XML, please check password: '"+response.substring(0,5)+"'");
} else {
lastXMLData=response;
txtStatus.setText("Resp Len: " + response.length());
skipUpdate=false;
updateFragmentListeners();
}
super.onPostExecute(result);
}
}
Now, when I get UnknownHostException, the app force close with following stack trace:
07-29 15:52:08.754 1525-1538/android.process.acore V/BackupServiceBinder﹕ doBackup() invoked
07-29 15:52:08.766 1525-1538/android.process.acore E/DictionaryBackupAgent﹕ Couldn't read from the cursor
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:71)
at android.os.Binder.execTransact(Binder.java:446)
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:64)
at android.os.Binder.execTransact(Binder.java:446)
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:57)
at android.os.Binder.execTransact(Binder.java:446)
I have no idea why this happen...
I tried to comment hte txtStatus.setText as normally it's not supposed to work from another thread, but no change.
Tested on android emulator with framework 22 and on my phone with framework 21.
Any idea would be welcome
Ok I manage to make it work using threads instead, here's final code:
public void getXMLData()
{
if (skipUpdate)
{
skipUpdate=false;
return;
}
skipUpdate=true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int SERVERPORT=0;
try {
SERVERPORT = Integer.parseInt(prefs.getString("pref_key_port_1","Port"));
} catch (NumberFormatException e) {
txtStatus.setText("Invalid Port Number");
return;
}
String SERVERHOST = prefs.getString("pref_key_host_1","127.0.0.1");
String PASSWORD = prefs.getString("pref_key_pass_1", "password");
try {
// XMLFetcherTask myXMLFetcherTask = new XMLFetcherTask(SERVERHOST,SERVERPORT,PASSWORD);
// myXMLFetcherTask.execute();
XMLFetcherTask XMLFetcherTaskThread = new XMLFetcherTask();
XMLFetcherTaskThread.dstAddress=SERVERHOST;
XMLFetcherTaskThread.dstPort=SERVERPORT;
XMLFetcherTaskThread.password=PASSWORD;
Thread cThread = new Thread(XMLFetcherTaskThread);
cThread.start();
} catch (Exception e) {
txtStatus.setText("Error "+e.getMessage());
return;
}
skipUpdate=false;
}
public class XMLFetcherTask implements Runnable {
String dstAddress;
int dstPort;
String response = "";
String password="";
private void setStatusFromThread(final String status)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
setStatus(status);
}
});
}
private void updateListenersThread()
{
runOnUiThread(new Runnable() {
#Override
public void run() {
updateFragmentListeners();
}
});
}
public void run() {
Socket socket = null;
//BufferedReader input = null;
//PrintWriter out = null;
try {
socket = new Socket(dstAddress, dstPort);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(password);
response="";
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (response.toLowerCase().indexOf("</response>") < 0) {
response+=input.readLine();
}
if( !(response.substring(0,5).equalsIgnoreCase("<resp") || response.substring(0,5).equalsIgnoreCase("<?xml")) ) //!response.substring(0,5).equalsIgnoreCase("<?xml") ||
{
setStatusFromThread("Server response doesn't look XML, please check password: '" + response.substring(0, 5) + "'");
} else {
lastXMLData=response;
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
setStatusFromThread("Last update: " + ft.format(dNow));
skipUpdate=false;
updateListenersThread();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("UnknownHostException: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("IOException: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("Exception: " + e.getMessage());
} finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//txtStatus.setText("Exception Finally: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
}
}

InetAddress.getByName () adds / to the ip

I'm having a weird problem. I'm creating a socket and giving it the IP 192.168.43.255. When I use InetAddress.getByName(IP) it adds / to the ip as shown in the log below. Why this is happening ??
here is my code
public class ServerCom extends AsyncTask<String, Void , String>{
private int port=9999;
private String IP="192.168.43.255";
private BufferedReader input;
private Socket socket;
private DataOutputStream toSer;
private InetAddress serverAddr;
private String LocationID;
File file;FileWriter writer;
#Override
protected String doInBackground(String... RSS) {
// TODO Auto-generated method stub
Log.d("s","async");
SandboxView.Locate=false;
try {
serverAddr = InetAddress.getByName(IP);
socket = new Socket(serverAddr, port);
toSer = new DataOutputStream(socket.getOutputStream());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// send result to server
try {
toSer.writeBytes(RSS[0]+"\n");
//get the response from server
LocationID=input.readLine();
toSer.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return LocationID;
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui
MainActivity.LocationID=LocationID;
SandboxView.Localization=MainActivity.CH2.getLocation(LocationID);
try {
writer = new FileWriter(file, true);
writer.append("room :"+LocationID+"\n");
writer.append(SandboxView.Localization.x+" "+SandboxView.Localization.y+"\n");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MainActivity.view.invalidate();
SandboxView.Locate=true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
05-16 17:53:16.331: W/System.err(3495): java.net.ConnectException: /192.168.43.255:9999 - Network is unreachable
This isn't really adding a / to the IP address, but the format of the address output by InetAddress.toString() uses a / to separate the hostname from the host address. See here. So, the / isn't really being added to the address, it is just shown in the logging.

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

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

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.

Categories

Resources