单向通信是指通信双方中,一方固定为发送端,一方则固定为接收端。
创建服务端
public class OneWaySocketServer {
public static void main(String[] args){
System.out.println("服务端启动,开始监听");
try(ServerSocket serverSocket = new ServerSocket(8888);
//监听8888端口,获取客户端对应的Socket对象
Socket socket = serverSocket.accept();
//通过与客户端对应的Socket对象获取输入流对象
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//通过与客户端对应的Socket对象获取输出流对象
PrintWriter pw = new PrintWriter(socket.getOutputStream())
){
System.out.println(连接成功!);
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();
System.out.println("服务端启动失败");
}
}
}
}
创建客户端
public class OneWaySocketClient {
public static void main(String[] args){
//获取与服务端对应的Socket对象
try(Socket socket = new Socket("127.0.0.1",8888);
//创建键盘输入对象
Scanner scanner = new Scanner(System.in);
//通过与服务端对应的Socket对象获取输入流对象
PrintWriter pw = new PrintWriter(socket.getOutputStream());
//通过与服务端对应的Socket对象获取输入流对象
BufferedReader 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();
}
}
}