//服务端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/*
* 创建一个多线程服务端
*
* 接收客户端发送过来的字符串
*
* 打印客户端的地址, 端口号, 发送过来的字符串
*
* 把字符串反转, 再发回去
*/
@SuppressWarnings("resource")
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(12345);
while (true) {
final Socket socket = serverSocket.accept();
new Thread(){
public void run() {
try {
String ip = socket.getInetAddress().getHostAddress();
int port = socket.getPort();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
String s = br.readLine(); // 读取到的一行字符串
System.out.println(ip + ":" + port + ": " + s); // 打印
ps.println(new StringBuilder(s).reverse()); // 反转, 发回去
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
//客户端
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
/*
* 连接服务端
*
* 从键盘接收一个字符串
*
* 发送到服务端
*
* 接收服务端发回的字符串, 打印
*/
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("192.168.3.100", 12345);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个字符串:");
ps.println(scanner.nextLine()); // 从键盘读取一行字符串, 发送
System.out.println(br.readLine()); // 从服务端读取一行字符串, 打印
socket.close();
scanner.close();
}
}
|