public class Test_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())); //获取输入流
OutputStream os = socket.getOutputStream();
String line = br.readLine(); //将客户端写过来的数据读取出来
System.out.println(line);
os.write(line.getBytes());
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
public class Test_Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
System.out.println("请输入一个字符串:");
Socket socket = new Socket("127.0.0.1", 54321); //创建客户端,指定ip地址和端口号
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //获取输入流
OutputStream os = socket.getOutputStream();
os.write(sc.nextLine().getBytes());
System.out.println(br.readLine()); //将反转后的结果读出来
socket.close();
}
} |