import java.io.*;
import java.net.*;
import java.util.Scanner;
public class TcpServer1// 服务端
{
public static void main(String[] args) throws Exception {
//這兩個都放在外面,
ServerSocket serverSocket = new ServerSocket(10001);
Socket s = serverSocket.accept();//客服端一直和服务器通信 连接一次就够了
try {
while (true) {
BufferedReader server_buf = new BufferedReader(
new InputStreamReader(s.getInputStream()));
String str = server_buf.readLine();
System.out.println("服务端接受到数据...");
Thread.sleep(2000);
PrintStream pri = new PrintStream(s.getOutputStream(), true);
System.out.println("服务端将字符串反转后发送给客户端...");
pri.println(new StringBuffer(str).reverse());// 将反转后的字符串打印到客户端屏幕上
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
class TcpClient// 客户端
{
public static void main(String[] args) throws Exception {
Socket s = null;
BufferedReader client_buf = null;
PrintStream pri = null;
Scanner sc = null;
try {
s = new Socket(InetAddress.getLocalHost(), 10001);
while (true) {
client_buf = new BufferedReader(new InputStreamReader(
s.getInputStream()));
pri = new PrintStream(s.getOutputStream(), true);
sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String str = sc.nextLine();
System.out.println("正在向服务器发送数据...");
pri.println(str);
System.out.println("接受来自服务器反转的字符串...");
System.out.println(client_buf.readLine());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
//声明最好都方法try{} 或循环的外面 这个是我的习惯 |