javaTCP单向通信
/**
* 实现TCP单向通信
*/
public class TCPOneWayCommunication extends Thread{
public boolean isServer;
public TCPOneWayCommunication(String name, boolean isServer) {
super(name);
this.isServer = isServer;
}
@Override
public void run() {
if (isServer){
runServer();
}else {
runClient();
}
}
public void runServer(){
ServerSocket ss = null;
Socket socket = null;
BufferedReader br = null;
PrintWriter pw = null;
try {
ss = new ServerSocket(8888);
System.out.println("服务端启动");
socket = ss.accept();
System.out.println("与客户端连接成功");
//当accept接收到客户端Socket对象才会唤醒线程向下执行连接成功语句
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
//PrintWriter自动换行设为true
for (String message = br.readLine();message!=null&&!"exit".equalsIgnoreCase(message);message = br.readLine()){
System.out.println("服务端线程 接收到客户端消息: "+message);
pw.println("以下消息已接收: "+message);
//.println()方法自动flush
}
pw.println("Bye~");
//当客户端Socket或客户端Socket的输出流关闭 或 客户端发送数据exit 后循环/通话结束
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
if (pw != null) {
pw.close();
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (ss != null) {
try {
ss.close();
//ServerSocket类的作用只在建立和客户端的连接,当连接建立成功即.accept返回Socket对象后即可关闭,实际通信使用Socket对象不受ServerSocket影响
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
public void runClient(){
try(Socket socket = new Socket("localhost",8888);
PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
Scanner sc = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
//"localhost"指本机地址,"localhost:8888"作用和"127.0.0.1:8888"作用相同
//Scanner对象用完之后也需要关闭,关闭时会将System.in关闭,而System.in是常量,关闭后直至程序结束都无法再打开
do {
System.out.print("客户端线程 请输入要发送给服务端的内容: ");
String message = sc.nextLine();
pw.println(message);
String respond = br.readLine();
System.out.println("客户端线程 服务器返回: "+respond);
//发送一句接收一句
if ("exit".equalsIgnoreCase(message))break;
}while (true);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
new TCPOneWayCommunication("服务端",true).start();
//先启动服务端再启动客户端
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
new TCPOneWayCommunication("客户端",false).start();
/*结果为:
服务端启动
与客户端连接成功
客户端线程 请输入要发送给服务端的内容: Hello World
服务端线程 接收到客户端消息: Hello World
客户端线程 服务器返回: 以下消息已接收: Hello World
客户端线程 请输入要发送给服务端的内容: eXIT
客户端线程 服务器返回: Bye~
*/
}
}