Android应用程序使用Socket发送和接收消息:

时间:2011-04-16 23:56:50

标签: java android sockets

我有一个Android应用程序,我试图使用套接字连接向服务器发送和接收消息。

我发送和接收各种问题。我一直都能做到这一点,而且两者都没有。

我想知道是否有人可以帮助我进行一项简单的练习,我可以使用BufferedReaderPrintWriter进行编译。

我很感激任何帮助,因为我正在放弃。

提前致谢....以下是我尝试过的一些镜头(尽管它们与这个问题无关,但我希望它表明我在此之前已经尝试过了)。

    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();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我只是忽略了关闭客户端的套接字连接。因此,虽然我怀疑我所做的是对我自己的问题的模型回答,但它包括在内。