嗨,我正在编写一个简单的 java 程序来从套接字读取数据,但遇到了一个问题,每次输入后我都会出现很多空格。
目的:编写一个简单的服务器套接字,它可以从客户端套接字读取正确的数据。
到目前为止:我已经能够编写从套接字读取的代码,甚至能够读取数据,但问题是我最后得到了很多空格。
所以我不得不使用trim(),最后来管理空间,但我仍然不知道这是对还是错。
将不胜感激这方面的投入。
注意:我正在使用 windows7 telnet 服务连接到套接字。
readSocket() {
System.out.println(client_socket);
try {
System.out.println("reading socket");
/*BufferedReader brIn = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
String inputLine = null;
while ((inputLine = brIn.readLine()) != null) {
System.out.println(inputLine);
}*/
InputStream is = client_socket.getInputStream();
byte[] byteArr = new byte[1024];
int inputsize = -1;
int currentPos = 0;
StringBuffer sb = new StringBuffer(11111);
/*while((inputsize = is.read(byteArr)) != -1) {
String processed = new String(byteArr);
sb.append(processed);
}*/
int BUFFER_SIZE = 1024;
int read;
byte[] buffer = new byte[BUFFER_SIZE];
String processed = "";
while ((read = is.read(byteArr, 0, BUFFER_SIZE)) != -1) {
String current = new String(byteArr);
//os.write(buffer, 0, read);
System.out.println("current Process "+current);
//processed +=current;
sb.append(current.toString().trim());
}
System.out.println("Socket input is : "+sb.toString());
System.out.println("Sending response to client "+processed.toString());
//client_socket.getOutputStream().write(sb.toString().getBytes());
//client_socket.getOutputStream().close();
FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\himanshu2100\\eee.txt"));
fos.write(processed.getBytes());
fos.close();
is.close();
client_socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
很好地使用了 Roger Lindsjö 和 mprivat 的建议,我重新设计了我从流中读取的部分。
readSocket() {
System.out.println(client_socket);
try {
System.out.println("reading socket");
InputStream is = client_socket.getInputStream();
byte[] byteArr = new byte[1024];
int read;
int BUFFER_SIZE = 1024;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((read = is.read(byteArr, 0, BUFFER_SIZE)) != -1) {
baos.write(byteArr, 0, read); //This is an optimized design, instead of having so many strings
}
System.out.println("Output is :"+new String(baos.toByteArray()));
baos.close();
is.close();
client_socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我希望这是一个更好的解决方案,所以发布它。欢迎提出建议。