客户端向服务器写字符串(键盘录入),
服务器(多线程)将字符串反转后写回,
客户端再次读取到是反转后的字符串
服务端
public class str_server {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(54321);
System.out.println("服务器启动,绑定54321端口");
while(true) {
final Socket socket = server.accept(); //接受客户端的请求
new Thread() { //开启一条线程
public void run() {
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));//获取输入流
PrintStream ps = new PrintStream(socket.getOutputStream());//获取输出流
String line = br.readLine(); //将客户端写过来的数据读取出来
line = new StringBuilder(line).reverse().toString();//链式编程
ps.println(line); //反转后写回去
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
客户端
public class str_client {
/**
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
Socket socket = new Socket("127.0.0.1", 54321); //创建客户端,指定ip地址和端口号
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));//获取输入流
PrintStream ps = new PrintStream(socket.getOutputStream());//获取输出流
ps.println(sc.nextLine()); //将字符串写到服务器去
System.out.println(br.readLine()); //将反转后的结果读出来
socket.close();
}
}