Client-Server TCP communication - android

The server should send a message "Hello :: enter QUIT to exit" to the client, then the client types in any text and the server echos back the client's text adding "From server: " before their message.
But there seems to be a mix up in the order and I can't seem to find where! I've been on this all day!
This is the Server's code:
import java.net.*;
public class Server {
public static void main(String[] args) {
int nreq = 1;
try
{
ServerSocket sock = new ServerSocket (8080);
for (;;)
{
Socket newsock = sock.accept();
System.out.println("Creating thread ...");
Thread t = new ThreadHandler(newsock,nreq);
t.start();
}
}
catch (Exception e)
{
System.out.println("IO error " + e);
}
System.out.println("End!");
}
}
ThreadHandler code:
import java.io.*;
import java.net.*;
class ThreadHandler extends Thread {
Socket newsock;
int n;
ThreadHandler(Socket s, int v) {
newsock = s;
n = v;
}
// #SuppressWarnings("deprecation")
public void run() {
try {
PrintWriter outp = new PrintWriter(newsock.getOutputStream(), true);
BufferedReader inp = new BufferedReader(new InputStreamReader(
newsock.getInputStream()));
outp.println("Hello :: enter QUIT to exit");
boolean more_data = true;
String line;
while (more_data) {
line = inp.readLine();
if (line == null) {
more_data = false;
} else {
outp.println("From server: " + line + "\n");
if (line.trim().equals("QUIT"))
more_data = false;
}
}
newsock.close();
} catch (Exception e) {
System.out.println("IO error " + e);
}
}
}
And the Client code:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
// #SuppressWarnings("deprecation")
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
try {
Socket s = new Socket("localhost", 8080);
PrintWriter outp = new PrintWriter(s.getOutputStream(), true);
BufferedReader inp = new BufferedReader(new InputStreamReader(
s.getInputStream()));
boolean more_data = true;
System.out.println("Established connection");
String line;
while (more_data) {
line = inp.readLine();
String userInput = scanner.nextLine();
outp.println(userInput);
if (line == null) {
more_data = false;
} else
System.out.println(line);
}
System.out.println("end of while");
} catch (Exception e) {
System.out.println("IO error " + e);
}
}
}
I'm testing it out so after I'm going to make the client an Android phone - if that's possible -
Update:
I've changed the server's code to:
outp.println("Hello :: enter QUIT to exit \n");
boolean more_data = true;
String line;
while (more_data) {
line = inp.readLine();
System.out.println("Message '" + line + "' echoed back to client.");// !!
if (line == null) {
System.out.println("line = null");
more_data = false;
} else {
outp.println("From server: " + line + ". \n");
if (line.trim().equals("QUIT"))
more_data = false;
}
}
newsock.close();
System.out.println("Disconnected from client number: " + n);
and added "\n" at the end of the Hello message as Luis Miguel Serrano suggested, And changed the Client's side as below:
boolean more_data = true;
System.out.println("Established connection");
String line;// = inp.readLine();
while (more_data) {
line = inp.readLine();
System.out.println(line);
if (line == null) {
// nothing read
more_data = false;
} else
line = inp.readLine();
System.out.println(line);
String userInput = scanner.nextLine();
if (userInput.trim() == "QUIT") {
s.close();
System.out.println("Disconnected from server.");
more_data = false;
} else
outp.println(userInput);
}
System.out.println("end of while");
And it works fine now.
If anyone could suggest me some Android client-java server tutorials would appreciate it.

In sequence of your comment, it could be a flushing issue. Try adding the following line:
outp.flush();
after:
outp.println("Hello :: enter QUIT to exit");
When you write to a stream, sometimes the things you write are kept in a buffer. If you want to make sure that buffer is emptied and the string is actually sent, you need to call the flush() method.
Update
Also, add "\n" to the end of your Hello welcome message from the server. I think that will make it work.

Related

some times MifareClassic 1k NFC card authentication failed while tag same card using android

I use MicareClassic 1k card that have data in sector 0 block 0 and 1. Data is in the format of
tagdata
And i try to read those blocks using following code segment
String resolveNfcIntent(Intent intent) {
final StringBuilder out=new StringBuilder();
String action = intent.getAction();
String msg = "";
String cardStudentId="";
String cardStudentName="";
String mifareKeyA="first 12 hex chars";
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
final Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
final byte keyByte[] = Util.hexStringToByteArray(mifareKeyA);
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
MifareClassic mfc = MifareClassic.get(tagFromIntent);
if (mfc == null) {
out.append("card not supported\n");
} else {
String msg;
try {
byte[] data;
out.append("Try to connect card\n");
mfc.connect();// caused IOException when close called from another thread;
out.append("card connected\n");
boolean authenticated = false;
final int SECTOR_INDEX = 0;
out.append("Try to authenticate with key A\n");
authenticated = mfc.authenticateSectorWithKeyA(SECTOR_INDEX, keyByte);
out.append("isCardAuthorizedWith Key A: " + authenticated + "\n");
if (authenticated) {
final int BLOCK_FIRST = mfc.sectorToBlock(SECTOR_INDEX);//Return the first block of a given sector.
final int BLOCK_ID = BLOCK_FIRST + 1;
final int BLOCK_NAME = BLOCK_FIRST + 2;
out.append("try to read id block " + BLOCK_ID + " \n");
data = mfc.readBlock(BLOCK_ID);//causes TagLostException, IOException
String cardStudentId = new String(data, Charset.forName("UTF-8")).trim();
out.append("id read: '" + cardStudentId + "'\ntry to read name block " + BLOCK_NAME + "\n");
data = mfc.readBlock(BLOCK_NAME);
String cardStudentName = new String(data, Charset.forName("UTF-8")).trim();
out.append("name read '" + cardStudentName + "'\n");
} else { // Authentication failed - Handle it
msg = "Nfc card Authentication failed";
out.append(msg + "\n");
Toast.makeText(MainActivity.this, "Nfc card Authentication failed", Toast.LENGTH_SHORT).show();
}
} catch (TagLostException e) {
msg = "Nfc card leaves before read";
out.append(msg + "\n");
} catch (IOException e) {
msg = "Nfc card IO error, try again later";
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
} catch (NullPointerException e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
out.append(sw.toString());
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
out.append(sw.toString());
} finally {
if (mfc != null) {
try {
out.append("try to close tag\n");
mfc.close();
out.append("tag closed\n");
} catch (IOException e) {
out.append("IOError in closing tag connection\n");
Log.e(TAG, "Error closing tag...", e);
}
}
}
}
mHandler.post(new Runnable() {
#Override
public void run() {
txt.setText(out.toString());
}
});
}
}).start();
}
return out.toString();
}
most cases it works well but some times it shows authentication failed error when authenticateWithKeyA() function called here.
i digging more but i can't find what the exact problem is. please guide me right direction.
Thanks

Passing special characters over socket connection

I have built a chat application in Android powered by sockets. The messages send and receive fine, so long as the user does not send messages with special characters, ie. Hey, it's me, will not work, but Hey its me, will, the comma and apostrophe prevent the message from being delivered.
I attempted using URLEncoder, but that did not allow the unique characters to be sent.
Sending message method:
public String sendMessage(String username, String tousername, String message, String campaign_id, String location_id)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&to=" + URLEncoder.encode(tousername, "UTF-8")
+ "&message=" + URLEncoder.encode(message, "UTF-8")
+ "&campaign_id=" + URLEncoder.encode(campaign_id, "UTF-8")
+ "&location_id=" + URLEncoder.encode(location_id, "UTF-8")
+ "&action=" + URLEncoder.encode("sendMessage", "UTF-8")
+ "&gcmregid=" + gcmRegistrationID
+ "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
with
SocketerInterface socketOperator = new Socketer(this);
and Socketer class as:
public class Socketer implements SocketerInterface {
// Have to set the proper ports that apache is runnign on as well as your
// computers IP address: ie. ip:4430 or 800
Global ipAddress = new Global();
private final String AUTHENTICATION_SERVER_ADDRESS = "http://"
// + ipAddress.getIpAddress() + ":80/AndroidChatterDatabase/"; // Google Compute Engine Access
//+ ipAddress.getIpAddress() + ":4430/AndroidChatterDatabase/"; // Localhost access
+ ipAddress.getFeastChatServer(); // For Heroku access
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket) {
this.clientSocket = socket;
Socketer.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new
// PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Log.v("XML MESSAGE", inputLine);
if (inputLine.equals("exit") == false) {// as long as have
// noted exited yet,
// will continuing
// reading in
Log.v("XML MESSAGE", inputLine);
// appManager.messageReceived(inputLine);
} else {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Socketer.this.sockets.remove(clientSocket
.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ", "");
}
}
}
public Socketer(Manager appManager) {
}
public String sendHttpRequest(String params) {
URL url;
String result = new String();
try {
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
// This is the output of the datastream from the server ie. <data>
// (bunch of data...etc) </data>
// Testing to remove <head/> tag from Google App Engine
//return result.replace("<head/>","");
return result;
}
public int startListening(int portNo) {
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
// e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
// e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket",
"Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening() {
this.listening = false;
}
public void exit() {
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator
.hasNext();) {
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e) {
}
}
sockets.clear();
this.stopListening();
}
public int getListeningPort() {
return this.listeningPort;
}
}
How can I format/encode to allow sending these messages?
Java uses UTF-16 for internal String representation, but it looks like you are using UTF-8, but you aren't doing anything special to convert it from UTF-8 when reading it from BufferedReader. In the params, try specifying UTF-16 instead.
From the Java String documentation:
A String represents a string in the UTF-16 format

Sending html content over server from android

I am trying to send html file content to request parameter.
The problem area is on the server side, getting some extra characters.
<!Document....> the other side ?<!Document...>
Why this "?" mark comes.
Can any one help me to figure out.
Thanks in advance.
Finally I got solution of my problem
import java.io.*;
public class UTF8ToAnsiUtils {
// FEFF because this is the Unicode char represented by the UTF-8 byte order mark (EF BB BF).
public static final String UTF8_BOM = "\uFEFF";
public static void main(String args[]) {
try {
if (args.length != 2) {
System.out
.println("Usage : java UTF8ToAnsiUtils utf8file ansifile");
System.exit(1);
}
boolean firstLine = true;
FileInputStream fis = new FileInputStream(args[0]);
BufferedReader r = new BufferedReader(new InputStreamReader(fis,
"UTF8"));
FileOutputStream fos = new FileOutputStream(args[1]);
Writer w = new BufferedWriter(new OutputStreamWriter(fos, "Cp1252"));
for (String s = ""; (s = r.readLine()) != null;) {
if (firstLine) {
s = UTF8ToAnsiUtils.removeUTF8BOM(s);
firstLine = false;
}
w.write(s + System.getProperty("line.separator"));
w.flush();
}
w.close();
r.close();
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static String removeUTF8BOM(String s) {
if (s.startsWith(UTF8_BOM)) {
s = s.substring(1);
}
return s;
}
}
You will find more detail in this link..
http://www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html

How to use port 502

I'm trying to develop an app which needs to have modbus/TCP. The default port for Modbus/TCP is 502. I'm getting an error when I try to open a connection on port 502. I tried different ports and they were working. I think something is blocking port 502, but I couldn't figure it out.
This is the exception I'm getting: 01-01 00:01:44.309: I/System.out(953): S: Error java.net.BindException: bind failed: EACCES (Permission denied)
I have "INTERNET" permission
Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer extends Thread {
public static final int SERVERPORT = 502;
public boolean running = true;
public boolean receiving = false;
private PrintWriter mOut;
public TCPServer() {
}
public void sendMessage(String message) {
if (mOut != null && !mOut.checkError()) {
mOut.println(message);
mOut.flush();
}
}
#Override
public void run() {
super.run();
try {
while (true) {
while (running) {
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
serverSocket.setSoTimeout(500);
Socket tempSckt = new Socket();
boolean isConnected = false;
while (!isConnected && running) {
try {
tempSckt = serverSocket.accept();
isConnected = true;
} catch (Exception e) {
}
}
if (running) {
System.out.println("connected");
final Socket client = tempSckt;
new Thread(new Runnable() {
#Override
public void run() {
receiving = true;
try {
mOut = new PrintWriter(client
.getOutputStream());
BufferedReader in = new BufferedReader(
new InputStreamReader(client
.getInputStream()));
while (receiving) {
String message = in.readLine();
if (message != null) {
// System.out.println(message);
byte[] bytes = message.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++) {
binary.append((val & 128) == 0 ? 0
: 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println("'" + message
+ "' to binary: " + binary);
} else {
receiving = false;
}
}
} catch (Exception e) {
System.out.println("S: Error"
+ e.toString());
} finally {
try {
client.close();
} catch (Exception e2) {
}
}
}
}).start();
isConnected = false;
}
serverSocket.close();
}
Thread.sleep(500);
}
} catch (Exception e) {
System.out.println("S: Error " + e.toString());
}
}
}
UPDATE
My Application running as a system app. I did the necessary configurations. I checked it with ps shell command. It is working as a system app now. But still I am not able to bind to port 502.
Ports below 1024 are restricted - only apps with root privileges can listen on those. Of course, your application isn't privileged.
That's the general rule on Linux/Unix (and Android is Linux-based).
See this answer for a rationale behind this restriction.

How to retrieve a file from http server

I have the following web server class found here. I need to write an Android application(client) which can retrieve a file from this server. It would be great if anyone would be able to help me to do it. Thank you.
Server host address is: My-PC/ipaddress
When I execute the client it gives an exception.
java.net.ConnectException: Connection refused: connect
WebServer.Java
import java.io.*;
import java.net.*;
public class WebServer extends Thread {
public WebServer() {
this.start();
}
private void displayString(String string) { //an alias to avoid typing so much!
System.out.println(string);
}
private static final int UMBRA_PORT = 30480;
private static final int ROOM_THROTTLE = 200;
private InetAddress hostAddress;
//this is a overridden method from the Thread class we extended from
public void run() {
//we are now inside our own thread separated from the gui.
ServerSocket serversocket = null;
//To easily pick up lots of girls, change this to your name!!!
displayString("The simple httpserver v. 0000000000\nCoded by Jon Berg" +
"<jon.berg[on server]turtlemeat.com>\n\n");
//Pay attention, this is where things starts to cook!
try {
//print/send message to the guiwindow
displayString("Trying to bind to localhost on port " + Integer.toString(UMBRA_PORT) + "...");
//make a ServerSocket and bind it to given port,
//serversocket = new ServerSocket(port);
}
catch (Exception e) { //catch any errors and print errors to gui
displayString("\nFatal Error:" + e.getMessage());
return;
}
// Attempt to get the host address
try
{
hostAddress = InetAddress.getLocalHost();
}
catch(UnknownHostException e)
{
System.out.println("Could not get the host address.");
return;
}
// Announce the host address
System.out.println("Server host address is: "+hostAddress);
// Attempt to create server socket
try
{
serversocket = new ServerSocket(UMBRA_PORT,0,hostAddress);
}
catch(IOException e)
{
System.out.println("Could not open server socket.");
return;
}
// Announce the socket creation
System.out.println("Socket "+serversocket+" created.");
displayString("OK!\n");
//go in a infinite loop, wait for connections, process request, send response
while (true) {
displayString("\nReady, Waiting for requests...\n");
try {
//this call waits/blocks until someone connects to the port we
//are listening to
Socket connectionsocket = serversocket.accept();
//figure out what ipaddress the client commes from, just for show!
InetAddress client = connectionsocket.getInetAddress();
//and print it to gui
displayString(client.getHostName() + " connected to server.\n");
//Read the http request from the client from the socket interface
//into a buffer.
BufferedReader input =
new BufferedReader(new InputStreamReader(connectionsocket.
getInputStream()));
//Prepare a outputstream from us to the client,
//this will be used sending back our response
//(header + requested file) to the client.
DataOutputStream output =
new DataOutputStream(connectionsocket.getOutputStream());
//as the name suggest this method handles the http request, see further down.
//abstraction rules
http_handler(input, output);
}
catch (Exception e) { //catch any errors, and print them
displayString("\nError:" + e.getMessage());
}
} //go back in loop, wait for next request
}
//our implementation of the hypertext transfer protocol
//its very basic and stripped down
private void http_handler(BufferedReader input, DataOutputStream output) {
int method = 0; //1 get, 2 head, 0 not supported
String http = new String(); //a bunch of strings to hold
String path = new String(); //the various things, what http v, what path,
String file = new String(); //what file
String user_agent = new String(); //what user_agent
try {
//This is the two types of request we can handle
//GET /index.html HTTP/1.0
//HEAD /index.html HTTP/1.0
String tmp = input.readLine(); //read from the stream
String tmp2 = new String(tmp);
tmp.toUpperCase(); //convert it to uppercase
if (tmp.startsWith("GET")) { //compare it is it GET
method = 1;
} //if we set it to method 1
if (tmp.startsWith("HEAD")) { //same here is it HEAD
method = 2;
} //set method to 2
if (method == 0) { // not supported
try {
output.writeBytes(construct_http_header(501, 0));
output.close();
return;
}
catch (Exception e3) { //if some error happened catch it
displayString("error:" + e3.getMessage());
} //and display error
}
//}
//tmp contains "GET /index.html HTTP/1.0 ......."
//find first space
//find next space
//copy whats between minus slash, then you get "index.html"
//it's a bit of dirty code, but bear with me...
int start = 0;
int end = 0;
for (int a = 0; a < tmp2.length(); a++) {
if (tmp2.charAt(a) == ' ' && start != 0) {
end = a;
break;
}
if (tmp2.charAt(a) == ' ' && start == 0) {
start = a;
}
}
path = tmp2.substring(start + 2, end); //fill in the path
}
catch (Exception e) {
displayString("errorr" + e.getMessage());
} //catch any exception
//path do now have the filename to what to the file it wants to open
displayString("\nClient requested:" + new File(path).getAbsolutePath() + "\n");
FileInputStream requestedfile = null;
try {
//try to open the file,
requestedfile = new FileInputStream(path);
}
catch (Exception e) {
try {
//if you could not open the file send a 404
output.writeBytes(construct_http_header(404, 0));
//close the stream
output.close();
}
catch (Exception e2) {}
displayString("error" + e.getMessage());
} //print error to gui
//happy day scenario
try {
int type_is = 0;
//find out what the filename ends with,
//so you can construct a the right content type
if (path.endsWith(".zip") ) {
type_is = 3;
}
if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {
type_is = 1;
}
if (path.endsWith(".gif")) {
type_is = 2;
}
if (path.endsWith(".ico")) {
type_is = 4;
}
if (path.endsWith(".xml")) {
type_is = 5;
}
//write out the header, 200 ->everything is ok we are all happy.
output.writeBytes(construct_http_header(200, 5));
//if it was a HEAD request, we don't print any BODY
if (method == 1) { //1 is GET 2 is head and skips the body
byte [] buffer = new byte[1024];
while (true) {
//read the file from filestream, and print out through the
//client-outputstream on a byte per byte base.
int b = requestedfile.read(buffer, 0,1024);
if (b == -1) {
break; //end of file
}
output.write(buffer,0,b);
}
//clean up the files, close open handles
}
output.close();
requestedfile.close();
}
catch (Exception e) {}
}
//this method makes the HTTP header for the response
//the headers job is to tell the browser the result of the request
//among if it was successful or not.
private String construct_http_header(int return_code, int file_type) {
String s = "HTTP/1.0 ";
//you probably have seen these if you have been surfing the web a while
switch (return_code) {
case 200:
s = s + "200 OK";
break;
case 400:
s = s + "400 Bad Request";
break;
case 403:
s = s + "403 Forbidden";
break;
case 404:
s = s + "404 Not Found";
break;
case 500:
s = s + "500 Internal Server Error";
break;
case 501:
s = s + "501 Not Implemented";
break;
}
s = s + "\r\n"; //other header fields,
s = s + "Connection: close\r\n"; //we can't handle persistent connections
s = s + "Server: SimpleHTTPtutorial v0\r\n"; //server name
switch (file_type) {
//plenty of types for you to fill in
case 0:
break;
case 1:
s = s + "Content-Type: image/jpeg\r\n";
break;
case 2:
s = s + "Content-Type: image/gif\r\n";
break;
case 3:
s = s + "Content-Type: application/x-zip-compressed\r\n";
break;
case 4:
s = s + "Content-Type: image/x-icon\r\n";
case 5:
s = s + "Content-Type: text/xml\r\n";
break;
default:
s = s + "Content-Type: text/html\r\n";
break;
}
////so on and so on......
s = s + "\r\n"; //this marks the end of the httpheader
//and the start of the body
//ok return our newly created header!
return s;
}
}
Client.Java
public class WatchMeManagerClient {
private static Socket socket;
private static PrintWriter printWriter;
public static void main(String[] args) throws Exception {
try {
URL url;
URLConnection urlConn;
DataInputStream dis;
url = new URL("http://ipaddress/xml/userGroup.xml");
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
dis = new DataInputStream(urlConn.getInputStream());
String s;
while ((s = dis.readLine()) != null) {
System.out.println(s);
}
dis.close();
}
catch (MalformedURLException mue) {
System.out.println(mue.toString());
} catch (IOException ioe) {
System.out.println(ioe.toString());
}
}
}
When I run the code on PC it works. But when I try to execute it on the Android Device it gives following errors.
Such problems are either due to one of the following:
The port is wrong
Firewall is stopping it.
Using Sockets require the following permission which I think you are missing:
<uses-permission android:name="android.permission.INTERNET" />
Did you allow internet access in your manifest?
<uses-permission android:name="android.permission.INTERNET"/>

Categories

Resources