Test_Java_网络编程(客户端向服务器发送字符串,服务器将字符串反转后发送给客户端)
需求: 客户端向服务器写字符串(键盘录入),服务器(多线程)将字符串反转后写回,客户端再次读取到是反转后的字符串
Test1_Client.java
package com.soar.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Test1_Client {
/*
* 客户端向服务器写字符串(键盘录入),服务器(多线程)将字符串反转后写回,
* 客户端再次读取到是反转后的字符串
*/
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();
}
}
Test1_Server.java
package com.soar.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Test1_Server {
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();
}
}
}