开发者

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.messa开发者_运维问答geToTranslate);
            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();
        }
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜