在服务器套接字java中从客户端获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18418326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get data from client in server socket java
提问by Shaggy
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
我能够连接客户端但无法从客户端接收数据
Data is being visible in my console only when THAT CLIENT GETS DISCONNECTED..!!!
仅当客户端断开连接时,数据才在我的控制台中可见..!!!
Code :-
代码 :-
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();
}
}
}
}
采纳答案by linski
Problem with your implementation
你的实现有问题
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') 或回车符后紧跟换行符中的任何一个结束。
In other words, if your client doesn't ever send \n
or \r
character that method will not end until the IOException
gets thrown as a result of disconnect.
换句话说,如果您的客户端从未发送\n
或\r
字符该方法将不会结束,直到IOException
由于断开连接而被抛出。
Solution
解决方案
Replace this code:
替换此代码:
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());
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.
从输入流中读取一定数量的字节并将它们存储到缓冲区数组 b 中。实际读取的字节数作为整数返回。此方法会阻塞,直到输入数据可用、检测到文件结尾或抛出异常。
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 Stringyou must know its encoding in order to show them correctly (that's the "UTF-8" part). If the encodingin which your client sends bytes is other, you might need to change it in order to get correct text in console output.
将在执行的确切时刻读取尽可能多的字节 - 它基本上是缓冲读取。由于这些是原始字节,因此在将它们转换为 String 时,您必须知道其编码才能正确显示它们(即“UTF-8”部分)。如果您的客户端发送字节的编码是其他的,您可能需要更改它以便在控制台输出中获得正确的文本。
I recommend reading the official tutorial lessons:
我建议阅读官方教程课程:
回答by RisingSun
Might be an issue with your ExecutorService (not?) being called.
可能是您的 ExecutorService(不是?)被调用的问题。
Try to subtitute
尝试替换
clientProcessingPool.submit(new ClientTask(clientSocket));
with
和
BufferedReader reader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String line;
while( (line = reader.readLine()) != null) // just read everything
System.out.println(line);
And see if you get any output at all.
看看你是否得到任何输出。
回答by rolfl
BufferedReader.readLine() will only return when there's an end-of-line or end-of-stream. Make sure the client side is sending a newline character, or use a different way to read the input stream like:
BufferedReader.readLine() 只会在有行尾或流尾时返回。确保客户端发送换行符,或使用不同的方式读取输入流,例如:
int ch = 0;
while ((ch = instream.read()) >= 0) {
// do sometyhing with the character off the input stream.
System.out.println("Got byte " + ch);
}
// will get here when the input stream is closed.