客户端和服务器之间使用套接字进行通信

时间:2011-04-16 21:14:42

标签: java android sockets

好的,这是今天早些时候的一个修改过的问题,我已经包含了帮助解释问题的代码。我从客户端向服务器发送两条消息。然后,服务器选择消息并处理它们。服务器最终尝试将消息发送回客户端(请注意服务器代码“testmessage”),我在这里遇到问题。要么我没有在客户端收到消息,要么从服务器端错误地发送消息。

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); 
    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();       
    br.close();
    //Log.d("application_name",translatedMessage); Trying to check the contents begin returned from the server.
    return translatedMessage;
}

服务器代码:

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"); // Test message!
        pw.flush(); 
        // Send off the data 
        pw.close();
        br.close();
        clientSocket.close();
        serverSocket.close();
    }
}
}

代码有点乱,我可以看到一些重复,我已经评论了我觉得问题出现的地方。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您正在使用BufferedReader.readLine()从服务器读取响应,但在测试用例中,您发送的字符串未以\ n或\ r \ n结尾,因此它不会获取该行据我所知,从文档......

public String readLine()
            throws IOException

Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

另外一个建议......

在编写这样的请求响应协议时,我不会依赖行结尾来终止请求或响应。通常我会使用完全格式化的JSON字符串,或者我的首选项是二进制协议,其中所有请求和响应都以二进制计数(通常为4字节bigendian /网络字节顺序)为前缀。然后客户端和服务器读取4个字节,然后读取后面的字节数。它处理通常通过网络连接发生的数据包碎片,也有助于避免恶意用户发送永远不会终止的长字符串的DOS攻击。

在Java中,您可以使用ByteBuffer.order()来处理bigendian数字。