【案例9-2】字符串反转
在使用软件或浏览网页时,总会查询一些数据,查询数据的过程其实就是客户端与服务器交互的过
程。用户(客户端)将查询信息发送给服务器,服务器接收到查询消息后进行处理,将查询结果返回给用(客户端)。本案例要求编写一 模拟客户端与服务器交互的程序,客户端向服务器传递一个字符串(键盘录入),服务器将字符串反转后写回,客户端再次接收到的是反转后的字符串 本案例要求使用多线程与 TCP 通信相关知识完成数据交互。
【实现代码】
/**
* ZAY 2023.7.31
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Example21 {
public static void main(String[] args) throws IOException, InterruptedException {
new Server().listen();
}
}
class Server {
private static int port = 6677;
public void listen() throws IOException, InterruptedException {
ServerSocket ss = new ServerSocket(port);
while (true){
Socket client = ss.accept();
new Thread(){
@Override
public void run() {
InputStream is = null;
try {
is = client.getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] buf = new byte[1024];
int len = 0;
try {
len = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
String str = new String(buf,0,len);
System.out.println("得到的数据为"+ str);
OutputStream os = null;
try {
os = client.getOutputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
String str1 = charAtReverse(str);
try {
os.write(str1.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("交互数据" + str1);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("结束");
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
client.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}.start();
}
}
public static String charAtReverse (String s){
int length = s.length();
String reverse = " ";
for (int i = 0; i < length; i++) {
reverse = s.charAt(i)+reverse;//字符串中获取单个字符的字符的放法
}
return reverse;
}
}
/**
* ZAY 2023.7.31
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Example22 {
public static void main(String[] args) throws IOException {
new Client().connect();
}
}
class Client {
private static int port = 6677;
public void connect() throws IOException {
Socket client = new Socket(InetAddress.getLocalHost(), port);
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
OutputStream os = client.getOutputStream();
os.write(str.getBytes());
InputStream is = client.getInputStream();
byte[] buf = new byte[1024];
int len = is.read(buf);
System.out.println(new String(buf, 0, len));
client.close();
}
}
【运行截图】