Categories
discuss

Android application using Socket to send and receive messages:

I have an android application that I am attempting to use to send and receive messages to a server using socket connection.

I have had all manner of problems sending and receiving. I have been able to do one or the other, at no point both.

I was wondering if someone could help me with a simple exercise that I can compile using BufferedReader and PrintWriter to do so.

I appreciate any help as I am at the point of giving up.

Thanks in advance…. Below are a few shots of what I have tried (Though they are irrelevant to this question, I hope it shows that I have tried before asking here).

    private OnClickListener sendClickListener = new OnClickListener(){
    public void onClick(View arg0) {

        Thread cThread = new Thread(new ClientThread());  
        cThread.start();  
}};    

public class ClientThread implements Runnable {  
    public void run() {  
        try {  
            EditText dstAddress = (EditText) findViewById(R.id.destinationAddress);
            EditText dstMessage = (EditText) findViewById(R.id.messageToTranslate);
            EditText dstPort = (EditText) findViewById(R.id.destinationPort);
            String address = dstAddress.getText().toString();   
            String message = dstMessage.getText().toString();
            int port = Integer.parseInt(dstPort.getText().toString());

            InetAddress serverAddr = InetAddress.getByName(address);  
            Log.d(".Coursework", "C: Connecting...");  

            Socket socket = new Socket(serverAddr, port);  
            connected = true;  
                while (connected) {  
                    try {  
                        EditText dstTranslation = (EditText) findViewById(R.id.returnedTranslation);
                        dstTranslation.setText("help me");
                        Log.d(".Coursework", "C: Sending command.");  
                        PrintWriter out;
                        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);  
                        out.println(language);
                        out.println(message);
                        Log.d("ClientActivity", "C: Sent.");  
                        //BufferedReader in;
                        //in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
                        //String translation = in.readLine();


                    } catch (Exception e) {  
                        Log.e("ClientActivity", "S: Error", e);  
                    }  
                }  
                socket.close();  
                Log.d("ClientActivity", "C: Closed.");  
        } catch (Exception e) {  
            Log.e("ClientActivity", "C: Error", e);  
            connected = false;  
        }  

    }

public class ClientConnection {

String address, language, message;
int portNumber;
Socket clientSocket = null;

public ClientConnection(String lan, String mes, String add, int pn) throws IOException{
    address = add;
    portNumber = pn;
    language = lan;
    message = mes;
}
public String createAndSend() throws IOException{
    // Create and connect the socket
    Socket clientSocket = null;
    clientSocket = new Socket(address, portNumber);
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(),true);
    BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));     

    // Send first message - Message is being correctly received
    pw.write(language+"n"); 
    pw.flush(); 
    // Send off the data  

    // Send the second message - Message is being correctly received
    pw.write(message+"n"); 
    pw.flush();
    pw.close();
    // Send off the data

    // NOTE: Either I am not receiving the message correctly or I am not sending it from the server properly.
    String translatedMessage = br.readLine();   
    System.out.print(translatedMessage);
    br.close();
    //Log.d("application_name",translatedMessage); Trying to check the contents begin returned from the server.
    return "Say What??";
}

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerConnection {

    public static void main(String[] args) throws Exception {       
        // Delete - Using while loop to keep connection open permanently.
        boolean status = false;
        while( !status){
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(4444);
            } catch (IOException e) {
                System.err.println("Could not listen on port: 4444.");
                System.exit(1);
            }
            Socket clientSocket = null;
            try {
                clientSocket = serverSocket.accept();
            } catch (IOException e) {
                System.err.println("Accept failed.");
                System.exit(1);
            }
            // Delete - Working as of here, connection is established and program runs awaiting connection on 4444
            BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));     
            String language = br.readLine();
            String message = br.readLine();
            // Test - Works
            System.out.println(language);      
            // Test - Works
            System.out.println(message);
            // Delete - Working as of here, both messages are passed and applied. Messages are received as sent from client.
            TranslateMessage tm = new TranslateMessage();
            String translatedMessage = tm.translateMessage(language, message);

            // NOTE: This seems to be where I am going wrong, either I am not sending the message correctly or I am not receiving it correctly..
            // PrintWriter writer = new PrintWriter(new BufferedOutputStream(clientSocket.getOutputStream()));
            PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(),true);
            // Send translation back 
            System.out.println(translatedMessage);
            pw.write(translatedMessage+"n"); 
            pw.write("Return test n"); // Test message!
            pw.flush(); 
            // Send off the data 
            pw.close();
            br.close();
            clientSocket.close();
            serverSocket.close();
        }
    }
}

Answer

I simply neglected to close the socket connection on the client side. So whilst I doubt what I have done is a model answer to my own question it works of included.

Categories
discuss

Why check for !isNaN() after isFinite()?

I came across the goog.math.isFiniteNumber function in the Google Closure Library. What it does is checking whether a given number is both finite and not NaN.

The underlying code is:

goog.math.isFiniteNumber = function(num) {
  return isFinite(num) && !isNaN(num);
};

So, first it checks whether the number is finite using the native isFinite function, and then does an additional check to make sure the number isn’t NaN using isNaN.

However, isFinite already returns false in case the argument is NaN. So, what advantages does the check for isNaN provide?

Answer

If isFinite worked the way isFiniteNumber did, then there would be no reason to write isFiniteNumber. There’s probably some browser out there somewhere that treats NaN as finite.

Categories
discuss

Access data in a JSON object (parsed) in JavaScript

I need to get the data “messages” from this JSON object. How can I do it in JavaScript?

To access for example the lastname I just use:

response[i].user.lastname

But how can I access the messages?

[
    {
        "user": {
            "last_message": {
                "message": {
                    "created_at": "2011-04-16T16:40:56Z",
                    "updated_at": "2011-04-16T16:40:56Z",
                    "to": null,
                    "id": 10,
                    "user_id": 28,
                    "message": "This is a message"
                }
            },
            "nickname": "thenicky",
            "id": 28,
            "lastname": "white",
            "firstname": "Sean",
            "bio": "A short bio",
            "email": "the@email.com"
        }
    }
]

Answer

response[i].user.last_message.message.created_at

And here’s a live demo.

Categories
discuss

Why does Java limit the size of a method to 65535 byte?

I just compiled the following code

public class A {
    public static void main(String... args) {
        int i = 3;
        ++i; 
        ++i;
        ++i;
        ++i;
        ++i;
        ++i;
        ++i;
        ++i;
        // repeat writing the expression ++i for 20,000 times

        System.out.println(i);
    }
}

And got the following error message

The code of method main(String…) is exceeding the 65535 bytes limit

Why does Java implement this limit? I don’t see the rational since Java does include a goto_w instruction.

Answer

See the Java Virtual Machine Specification section 4.10:

4.10 Limitations of the Java Virtual Machine

  • The amount of code per non-native, non-abstract method is limited to 65536 bytes by the sizes of the indices in the exception_table of the Code attribute (§4.7.3), in the LineNumberTable attribute (§4.7.8), and in the LocalVariableTable attribute (§4.7.9).

There’s few good reasons to have a method that long in an object-oriented programming language.

Categories
discuss

Android text shadow units

Android text shadows have shadowDx and shadowDy to specify the shadow’s offset. These are floats and are a factor rather than absolute units. The answer given here implies that there’s no easy way of specifying the shadow’s position in pixels or dips: TextView:shadowDx/Dy/Radius in dip?

So… what do the units mean? If I give a shadowDx of 1.5, that’s 1.5 what? 1.5 times the text size?

Answer

OK, I guess the units are physical pixels. The fact that the documentation doesn’t state what the units are (it just says “Must be a floating point value”), and that you don’t get to choose which units (pixels or dip), was confusing me.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..