tcp-server/src/test/java/com/zhangmeng/AppTest3.java

80 lines
2.4 KiB
Java

package com.zhangmeng;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* @author zm
* @date 2025/2/22 15:43
* @version: 1.0
*/
public class AppTest3 {
public static void main(String[] args) {
Socket socket = null;
BufferedReader in = null;
BufferedWriter out = null;
BufferedReader br = null;
try {
//创建 Socket 对象,指定服务器端的 IP 与端口
socket = new Socket(InetAddress.getLocalHost(), 9999);
//获取 scoket 的输入输出流接收和发送信息
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new
OutputStreamWriter(socket.getOutputStream()));
br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
//发送信息
String str = "br.readLine()";
out.write(str + "\n");
out.flush();
//如果输入的信息为“end”则终止连接
if (str.equals("end")) {
break;
}
//否则,接收并输出服务器端信息
System.out.println("服务器端说:" + in.readLine());
Thread.sleep(1000);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
// 关闭资源
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}