繁体   English   中英

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

[英]Communication between Client and Server using 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();
    }
}
}

代码有点混乱,我可以看到一些重复的地方,我在出现问题的地方发表了评论。

谢谢你的帮助!

您正在使用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()处理双端数字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM