实现代码:
ReverseServer.java文件代码:
import java.net.*;
public class ReverseServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ServerSocket ss = new ServerSocket(8001);
boolean bRunning = true;
while (bRunning) {
Socket s = ss.accept();
new Thread(new Servicer(s)).start();
}
ss.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Servicer.java文件代码:
import java.net.*;
import java.io.*;
public class Servicer implements Runnable {
private Socket s = null;
public Servicer(Socket s) {
this.s = s;
}
public void run() {
try {
InputStream ips = s.getInputStream();
OutputStream ops = s.getOutputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(ips));
PrintWriter pw = new PrintWriter(ops,true);
while (true) {
String strLine = br.readLine();
if(strLine.equalsIgnoreCase("quit"))
{
break;
}
String strEcho = (new StringBuffer(strLine).reverse()).toString();
pw.println(strLine + "-->" + strEcho);
}
br.close();
pw.close();
s.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
运行结果:
现在Eclipse里面运行ReverseServer,再启动3个cmd窗口,运行telnet客户端:
为什么会产生这样的结果,因为其实输入了5个字符abd{Backspace}c这样会显示abc,当反过来是就成了c{Backspace}dba就会显示dba。