从服务器套接字java中的客户端获取数据 [英] get data from client in server socket java

查看:137
本文介绍了从服务器套接字java中的客户端获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个执行以下任务的服务器应用程序

I am creating a server app which does the following task


  • 接受来自客户端的连接

  • 将每个客户端连接处理为单独的线程

  • 从客户端接收数据

  • 将数据发送到客户端

  • Accept connection from client
  • Process each client connection to separate thread
  • Receive data from client
  • send data to client

我能够连接客户端但无法从客户端接收数据

I am able to connect client but not able to receive data from client

数据在我的控制台中可见只有当客户端断开连接时...... !!!

代码: -

public class ServerListener {

    public static void main(String[] args) {
        new ServerListener().startServer();
    }

    public void startServer() {
        final ExecutorService clientProcessingPool = Executors
                .newFixedThreadPool(10);

        Runnable serverTask = new Runnable() {
            @Override
            public void run() {
                try {
                    ServerSocket serverSocket = new ServerSocket(8000);
                    System.out.println("Waiting for clients to connect...");
                    while (true) {
                        Socket clientSocket = serverSocket.accept();
                        clientProcessingPool
                                .submit(new ClientTask(clientSocket));
                    }
                } catch (IOException e) {
                    System.err.println("Unable to process client request");
                    e.printStackTrace();
                }
            }
        };
        Thread serverThread = new Thread(serverTask);
        serverThread.start();
    }

    private class ClientTask implements Runnable {
        private final Socket clientSocket;

        private ClientTask(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            System.out.println("Got a client !");
            try {
            /* Get Data From Client */
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream()));
                String clientData = "";
                clientData = reader.readLine();
                System.out.println("Data From Client :" + clientData);

            /* Send Data To Client */

                //Code

                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


推荐答案

您的实施问题



BufferedReader #readLine

Problem with your implementation

BufferedReader#readLine:


读取一行文字。一条线被认为是由换行符('\ n'),回车符('\ r')或回车符后面的任何一个终止。

Reads 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.

换句话说,如果您的客户没有发送 \ n \ r 该字符只有在因断开连接而抛出 IOException 时该方法才会结束。

In other words, if your client doesn't ever send \nor \r character that method will not end until the IOException gets thrown as a result of disconnect.

替换此代码:

BufferedReader reader = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));
String clientData = "";
clientData = reader.readLine();

with:

int red = -1;
byte[] buffer = new byte[5*1024]; // a read buffer of 5KiB
byte[] redData;
StringBuilder clientData = new StringBuilder();
String redDataText;
while ((red = clientSocket.getInputStream().read(buffer)) > -1) {
    redData = new byte[red];
    System.arraycopy(buffer, 0, redData, 0, red);
    redDataText = new String(redData,"UTF-8"); // assumption that client sends data UTF-8 encoded
    System.out.println("message part recieved:" + redDataText); 
    clientData.append(redDataText);
}
System.out.println("Data From Client :" + clientData.toString());

InputStream #read


从输入流中读取一些字节数并将它们存储到缓冲区数组b中。实际读取的字节数以整数形式返回。此方法将阻塞,直到输入数据可用,检测到文件结尾或抛出异常。

Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

将读取多个字节它可以在执行的确切时刻 - 它基本上是缓冲读取。因为这些是原始字节,所以将它们转换为字符串你必须知道它的编码才能正确显示它们(那就是UTF-8部分)。如果您的客户端发送字节的编码是其他的,您可能需要更改它以便在控制台输出中获取正确的文本。

will read as many bytes as it can at the exact moment of its execution - it is basically buffered reading. Since these are raw bytes, when converting them to String you must know its encoding in order to show them correctly (that's the "UTF-8" part). If the encoding in which your client sends bytes is other, you might need to change it in order to get correct text in console output.

我建议阅读官方教程:

  • Byte streams
  • Character streams
  • Buffered streams

这篇关于从服务器套接字java中的客户端获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆