服务器端
package tcp;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
/**
* 英译汉服务器
*/
public class TCPServerByCN {
// 端口号
private static final int port = 9003;
// 翻译字典
static HashMap<String, String> dirMap = new HashMap<>();
static {
dirMap.put("hello", "你好");
dirMap.put("dog", "狗");
dirMap.put("cat", "猫");
}
public static void main(String[] args) throws IOException {
// 1.创建 TCP 服务器端
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("已启动服务器端");
// 2.等待客户端连接
Socket socket = serverSocket.accept();
System.out.println(String.format("已有客户端连接,IP:%s,Port:%d",
socket.getInetAddress().getHostAddress(),
socket.getPort()));
// 执行到此行,说明已经有客户端连接
// 3.创建读、写对象
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()))
) {
while (true) {
// 4.获取到待翻译的英文内容
String en = reader.readLine();
if (en != null && !en.equals("")) {
// 5.将英文翻译成中文
String cn = processData2(en);
// 6.将翻译结果返回给客户端
writer.write(cn + "\n");
writer.flush();
}
}
}
}
// 英译汉实现方法 1
private static String processData(String en) {
String cn = "未知";
switch (en) {
case "hello":
cn = "你好";
break;
case "dog":
cn = "狗";
break;
case "cat":
cn = "猫";
break;
default:
cn = "未知";
break;
}
return cn;
}
// 英译汉实现方法 2
private static String processData2(String en) {
String cn = null;
cn = dirMap.get(en);
return cn == null ? "未知" : cn;
}
}
客户端
package tcp;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class TCPClient {
// 服务器IP
private static final String ip = "127.0.0.1";
// 服务器端口号
private static final int port = 9003;
public static void main(String[] args) throws IOException {
// 1.创建并启动客户端,随便连接服务器端
Socket socket = new Socket(ip, port);
// 2.创建收、发消息对象
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in)
) {
while (true) {
System.out.print("请输入英文:");
// 3.构建消息
String msg = scanner.nextLine();
// 4.发送消息
writer.write(msg + "\n");
// 将发送缓冲区的消息立即发送
writer.flush();
// 5.接收服务器端的消息
String serMsg = reader.readLine();
if (serMsg != null && !serMsg.equals("")) {
System.out.println("中文:" + serMsg);
}
}
}
}
}
效果展示