TCP(四):要求客户端向服务器写字符串(键盘录入),服务器(多线程)将字符串反转后写回,客户端再次读取到是反转后的字符串
1、示例代码如下:
客户端:
package com.jh.www;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class Test4_Client {
/*
* 客户端向服务器写字符串(键盘录入),服务器(多线程)将字符串反转后写回,
* 客户端再次读取到是反转后的字符串
* */
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1",12345);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(os);
Scanner sc = new Scanner(System.in);
System.out.println("请输入一行字符串:");
String str = sc.nextLine();
ps.println(str);
String result = br.readLine();
System.out.println(result);
socket.close();
}
}
服务端:
package com.jh.www;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Test4_Server {
/*
* 客户端向服务器写字符串(键盘录入),服务器(多线程)将字符串反转后写回,
* 客户端再次读取到是反转后的字符串
* */
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(12345);
while(true) {
Socket socket = server.accept();
new Thread () {
public void run() {
try {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(os);
String str = br.readLine();
System.out.println(str);
String result = new StringBuilder(str).reverse().toString();
ps.println(result);
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
}