1.创建服务端

package com.yqq.app2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
* @Author yqq
* @Date 2021/11/04 22:29
* @Version 1.0
*/
public class oneWaySocketServer {
public static void main(String[] args) {
BufferedReader br = null;
Socket socket = null;
PrintWriter pw = null;
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务端启动,等待监听");
socket = serverSocket.accept();
System.out.println("连接成功");
//读取客户端发送的消息
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//向客户端写回消息的流对象
pw = new PrintWriter(socket.getOutputStream());
while (true){
String str = br.readLine();
System.out.println("客户端谁:"+str);
if("exit".equals(str))
break;
pw.println(str);
pw.flush();
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(pw !=null)
pw.close();
if(socket!=null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

TCP 单向通信_网络协议

2.创建客户端

package com.yqq.app2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
* @Author yqq
* @Date 2021/11/04 22:49
* @Version 1.0
*/
public class oneWaySocketClient {
public static void main(String[] args) {
Socket socket =null;
Scanner scanner =null;
PrintWriter pw = null;
BufferedReader br =null;
try {
socket = new Socket("127.0.0.1",8888);
//创建键盘输入对象
scanner = new Scanner(System.in);
//创建服务端输出消息的流对象
pw = new PrintWriter(socket.getOutputStream());
//创建服务端返回消息的流对象
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true){
//通过键盘输入获取向服务端发送的消息
String str = scanner.nextLine();
//将消息发送服务端
pw.println(str);
pw.flush();
if("exit".equals(str))
break;
//读取服务端返回的消息
String serverInput = br.readLine();
System.out.println("服务端返回的"+serverInput);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(scanner!=null)
scanner.close();
if(br!=null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(pw!=null)
pw.close();
if(socket!=null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

TCP 单向通信_java_02