I am writing a code that needs to send data from Android mobile to desktop computer (linux server) every second. Since the data is send very often, this cannot be achieved via Http hit (as it consumes times), Tcp communication seems a better option as the data from android phone can be send very quickly through this socket programming.
The code of client on Android phone is:
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class GetWebPage extends Activity {
//Handler h;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText eText = (EditText) findViewById(R.id.address);
final TextView tView = (TextView) findViewById(R.id.pagetext);
final Button button = (Button) findViewById(R.id.ButtonGo);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
Log.v("Tcp","Clicked the button");
InetAddress serveraddress=InetAddress.getByName("67.23.14.156");
Log.v("Tcp", "Got the InetAddress");
Socket s = new Socket(serveraddress,4447);
Log.v("Tcp","Got the Socket address");
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("Hello Android!");
out.close();
} catch (UnknownHostException e) {
tView.setText(e.toString());
Log.v("Tcp",e.toString());
} catch (IOException e) {
tView.setText(e.toString());
Log.v("Tcp",e.toString());
}catch (Exception e) {
tView.setText(e.toString());
}
}
});
}
}
The server side code is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ListenIncomingTcpConnection {
public static void main(String[] args) {
ServerSocket serverSocket=null;
Socket client=null;
try {
System.out.println("Creating the server object...");
serverSocket = new ServerSocket(4447);
System.out.println("Waiting for the connection...");
} catch (IOException e1) {
System.out.println(e1);
}
while (true) {
try {
client = serverSocket.accept();
System.out.println("Reading the content...");
} catch (IOException e1) {
System.out.println(e1);
e1.printStackTrace();
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("Reading the content.....");
} catch(Exception e) {
System.out.println(e);
} finally {
try{
client.close();
}catch(Exception e){
System.out.println(e);
}
}
}//while
}//PSVM
}
The code of manifest file is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spce" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="GetWebPage">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
</manifest>
I have executed the server code on the linux machine via "java" command on putty. It executed and stopped at this line "client = serverSocket.accept();"
When I execute the client on android mobile, it says:
Clicked the button
Got the InetAddress
java.net.SocketException: No route to host
I am not able to spot the reason of this No route to host.
Please help in solving the problem.
Looks like you're doing a DNS lookup on an IP address
serveraddress=InetAddress.getByName("67.23.14.156")
Try to use the IP address directly.
new Socket("67.23.14.156",4447);
Related
My problem when I try to send a simple "hello world" msg from the pc "client " to the phone "server " and
I tried all possible solution like : starting the server app which is on the phone first then the client but didn't work,
I changed the ip address too but didn't work,
I closed the firewall nothing happened too
Server's code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
public class Server{
public void main(String args[]) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(5000);} catch (IOException e) {
e.printStackTrace();
}
while (true) {
// Wait for a client connection.
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
// Create and start a thread to handle the new client
try {
// Get the socket's InputStream, to read bytes
// from the socket
InputStream in = clientSocket.getInputStream();
// wrap the InputStream in a reader so you can
// read a String instead of bytes
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, Charset.forName("UTF-8")));
// Read from the socket and print line by line
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(getApplicationContext(),line,Toast.LENGTH_LONG).show();
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
// This finally block ensures the socket is closed.
// A try-with-resources block cannot be used because
// the socket is passed into a thread, so it isn't
// created and closed in the same block
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}}
Client's code:
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class ClientClass {
public static void main(String args[]) {
try (Socket socket = new Socket("192.168.1.3", 5000);) {
// We'll reach this code once we've connected to the server
// Write a string into the socket, and flush the buffer
OutputStream outStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
writer.println("Hello world!");
writer.flush();
} catch (IOException e) {
// Exception should be handled.
e.printStackTrace();
}
}
}
error:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at ClientClass.main(ClientClass.java:10)
BUILD SUCCESSFUL (total time: 2 seconds)
I was having same error, and i managed to know what causes this error in my case, you have to check two things:
1-Router configuration if you are connected using WiFi because you have to forward your port correctly.(How to Set Up Port Forwarding on a Router, it differs according to router type)
2-If this IP address here is the correct IP address of your mobile or not:
Socket socket = new Socket("192.168.1.3", 5000);
(How To Check Your Android IP Address)
In the MainActivity class, the inner class named Server is never instantiated and the "main" method is neither called too.
Please have a look to this Tutorial post so as to have an example of how to implement a server using sockets with android devices.
I want to transfer a file between two devices, a server and a client .. I have a little problem on the client side.
I got this error in logcat:
java.lang.ArrayIndexOutOfBoundsException: length=1024; regionStart=0; regionLength=-1
please if my codes are wrong tell me. I want to make an app and its 4 days i am working on transfering. it get to me awful. please help
this is the client:
package com.example.test;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;
import android.os.Environment;
public class MainActivity extends ActionBarActivity {
EditText editTextAddress;
Button buttonConnect;
TextView textPort;
static final int SocketServerPORT = 8000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.address);
textPort = (TextView) findViewById(R.id.port);
textPort.setText("port: " + SocketServerPORT);
buttonConnect = (Button) findViewById(R.id.connect);
buttonConnect.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
ClientRxThread clientRxThread =
new ClientRxThread(
editTextAddress.getText().toString(),
SocketServerPORT);
clientRxThread.start();
}});
}
private class ClientRxThread extends Thread {
String dstAddress;
int dstPort;
ClientRxThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
File file = new File(
Environment.getExternalStorageDirectory(),
"input.jpg");
byte[] bytes = new byte[1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
bos.close();
socket.close();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
"Finished",
Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eMsg,
Toast.LENGTH_LONG).show();
}});
} finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
client xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.androidsocketfiletransferclient.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="File Transfer Client"
android:textStyle="bold" />
<EditText
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="dstAddress" />
<TextView
android:id="#+id/port"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connect..." />
client manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
server :
package com.example.testserverandroid;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
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.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
TextView infoIp, infoPort;
static final int SocketServerPORT = 8000;
ServerSocket serverSocket;
ServerSocketThread serverSocketThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoIp = (TextView) findViewById(R.id.infoip);
infoPort = (TextView) findViewById(R.id.infoport);
infoIp.setText(getIpAddress());
serverSocketThread = new ServerSocketThread();
serverSocketThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
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 += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public class ServerSocketThread extends Thread {
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
FileTxThread fileTxThread = new FileTxThread(socket);
fileTxThread.start();
}
} 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();
}
}
}
}
}
public class FileTxThread extends Thread {
Socket socket;
FileTxThread(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory(),
"test.txt");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
OutputStream os = socket.getOutputStream();
os.write(bytes, 0, bytes.length);
os.flush();
socket.close();
final String sentMsg = "File sent to: "
+ socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, sentMsg,
Toast.LENGTH_LONG).show();
}
});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
server manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
In your client, when you are reading from the input stream, the number of bytes read will be -1 if you are already at the end of the stream. This is described in the documentation for InputStream.
The ArrayIndexOutOfBoundsException exception occurs when this statement executes and bytesRead is -1.
bos.write(bytes, 0, bytesRead);
You need to restructure your client code that reads the input stream to check for end-of-stream.
Replace this:
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
With this:
int bytesRead;
while ((bytesRead = is.read(bytes)) > 0) {
bos.write(bytes, 0, bytesRead);
}
I have written a small client server application for android. The client is a Java program running on my PC while my Android phone is a server. I'm facing force close issues in my server program. The server starts pretty good, but when I send a string from my PC client, the android application (server) force closes. It has become really annoying. Please help!
Here is my client program running on my PC:
package javaNetPackage;
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.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
public class javaClient {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String serverIpAddress = "10.81.242.220";
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
echoSocket = new Socket(serverAddr, 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to server");
System.exit(1);
}
String str = JOptionPane.showInputDialog("Please give number");
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(echoSocket.getOutputStream())),true);
out.println(str);
out.close();
in.close();
echoSocket.close();
}
}
And here is my server code running on Android:
package com.vinit.androidserver;
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;
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 = 4444;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText("Nothing from client yet");
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
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.textView1);
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();
}
}
}
}
}
Permissions:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Update:: Okay, I solved the issue of force close. I deleted the permission tags in manifest.xml and re-typed them. But now, I'm facing a different problem here. The sent string from PC client is not getting displayed in my server TextView (textView1 in layout xml, referred to as tv in server code). Default message in tv is "Nothing from client yet". When I send a string from PC client, default message disappears but sent string is not updated in server TextView (tv).
You should set the received string to your Message object sent in myUpdateHandler.sendMessage(m); instead of your mClientMsg field.
You can create and send the Message object as below:
String st = null;
st = input.readLine();
Message msg = Message.obtain(myUpdateHandler, MSG_ID, st);
msg.sendToTarget();
To get the value in your handler,
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText((String) msg.obj);
break;
I would suggest you use a Bundle object instead of the raw object though. http://developer.android.com/reference/android/os/Message.html#setData(android.os.Bundle)
The reason you ends up with an empty string is because your handler and CommsThread run in different threads and thus not using the same instance of mClientMsg.
i.e. changes in CommsThread to mClientMsg is not visible in your handler.
I want to connect to my server building in Android, but I can't, I don't know how to connect it. I think my code is fine. I changed Manifest with Permission INTERNET.
package com.android.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private static String TAG = "ServerSocketTest";
EditText edittext1;
private ServerSocket server;
Runnable conn = new Runnable() {
public void run() {
try {
edittext1.setText("Esperando0");
server = new ServerSocket(9999);
edittext1.setText("Esperando1");
while (true) {
edittext1.setText("Esperando2");
Socket socket = server.accept();
if(socket.isConnected() == true){
edittext1.setText("socket is connected: " + socket.getRemoteSocketAddress().toString());
}
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Toast.makeText(getApplicationContext(), "BufferedReader ready", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
Log.i("received response from server", str);
edittext1.setText("Conectado");
PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
salida.println("Conexion establecida");
in.close();
socket.close();
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
};
#SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
edittext1 = (EditText)findViewById(R.id.editText1);
Button boton1 = (Button)findViewById(R.id.button1);
boton1.setOnClickListener(this);
new Thread(conn).start();
}
#Override
protected void onPause() {
super.onPause();
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void onClick(View v) {
}
}
My client, it work very well.:
package com.clientesocketandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ClienteSocketAndroid extends Activity implements OnClickListener{
String IP,mensaje, MensajeEntrada;
int Port;
Socket socket;
ServerSocket SSocket;
PrintWriter out;
Button boton1, boton2,boton3;
EditText edittext1,edittext2,edittext3,edittext4;
TextView textview5;
String mClientMsg = "";
Thread myCommsThread = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cliente_socket_android);
boton1 = (Button)findViewById(R.id.button1);
boton1.setOnClickListener(this);
boton2 = (Button)findViewById(R.id.button2);
boton2.setOnClickListener(this);
boton3 = (Button)findViewById(R.id.button3);
boton3.setOnClickListener(this);
edittext1 = (EditText)findViewById(R.id.editText1);
edittext2 = (EditText)findViewById(R.id.editText2);
edittext3 = (EditText)findViewById(R.id.editText3);
edittext4 = (EditText)findViewById(R.id.editText4);
Port = Integer.parseInt(edittext3.getText().toString());
try {
SSocket = new ServerSocket(Port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket = SSocket.accept();
Toast.makeText(getApplicationContext(), "Listo", Toast.LENGTH_SHORT).show();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
MensajeEntrada = in.readLine();
edittext4.setText(MensajeEntrada);
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
public void onClick(View arg0) {
if(arg0.getId() == R.id.button1){
try {
IP = edittext2.getText().toString();
Port = Integer.parseInt(edittext3.getText().toString());
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
socket = new Socket(IP, Port); //Abre un socket con el número de IP y de puerto.
if(socket.isConnected() == true){
Toast.makeText(getApplicationContext(), "Conectado", Toast.LENGTH_SHORT).show();
}
} catch (UnknownHostException e) {
e.printStackTrace();
edittext1.setText(e.getMessage() + ": " + e.getCause());
} catch (IOException e) {
e.printStackTrace();
edittext1.setText(e.getMessage() + ": " + e.getCause());
}
}
if(arg0.getId() == R.id.button3){
try {
mensaje = edittext1.getText().toString();
PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
salida.println(mensaje);
edittext1.setText("");
//hace falta concatenacion
edittext4.setText("" + "\n" + mensaje + "");
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Mensaje NO enviado", Toast.LENGTH_SHORT).show();
}
}
if(arg0.getId() == R.id.button2){
try {
PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
salida.println("bye");
Toast.makeText(getApplicationContext(), "Conexión cerrada", Toast.LENGTH_SHORT).show();
socket.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error al cerrar sesion", Toast.LENGTH_SHORT).show();
}
}
}
}
I thank your Help!!
The algorithm shows that whenever your socket is connected or not, you always create a buffered i/O stream and sending the data
The following is my suggested pseudo code for server
try(socket successfully connected) {
try( server is synchronized with the client) socket.accept();
// create the Object I/O stream
} show error
for Client
//Create a new socket with IP address and port number
try
client connect to server with aforementioned parameters with timeout
create a Object I/O stream
catch (IOException)
One problem that I see with your code is, you cannot update Ui elements from Non Ui thread, that is why it is raising exception, but you have caught all the exceptions.
So remove all setText calls from the runnable.
edittext1.setText("Conectado");
Use runonUithread or any other methods to update UI elements, and do not catch all exceptions like you have done. It is quite difficult to debug.
A simple socket app in Android needs some special permissions to connect through the internet?
Whats wrong with my code? It always get Exceptions when it tryes to connect to input text IP, or HOST.
package What.HTTPServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class WhatHTTPServerActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
TextView text = (TextView)findViewById(R.id.textView4);
EditText textField = (EditText) findViewById(R.id.editText1);
if (textField.getText().toString().length() > 3)
{
String host = textField.getText().toString();
String retorno = "";
text.setTextColor(0xff0000ff);
text.setText("Connecting...");
try {
Socket s = new Socket(host, 80);
//outgoing stream redirect to socket
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
// send an HTTP request to the web server
output.println("GET / HTTP/1.1");
output.println("Host: " + host + ":80");
output.println("Connection: Close");
output.println();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
// read the response
boolean loop = true;
StringBuilder sb = new StringBuilder(8096);
while (loop) {
if (in.ready()) {
int i = 0;
while (i != -1) {
i = in.read();
sb.append((char) i);
}
loop = false;
}
}
retorno = sb.toString();
//Close connection
s.close();
text.setTextColor(0xff0000ff);
text.setText("Your server runs: \n"
+ retorno );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
text.setTextColor(0xffff0000);
text.setText("Error! The Host or IP is unknown." );
} catch (IOException e) {
// TODO Auto-generated catch block
text.setTextColor(0xffff0000);
text.setText("Unknown error. Check your internet connection!" );
}
} else {
text.setTextColor(0xffff0000);
text.setText("Error! Please type your host or IP" );
}
}
}
Do you have
<uses-permission android:name="android.permission.INTERNET" />
in your manifest? Outside the application tags.
Any internet access from your application requires the internet acces permisison.
Android Permissions
The permission you want is called "INTERNET"