import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; /** * socket消息接收方 * @author BHL-lang * */ public class SocketReciveTest { public static void main(String[] args) throws UnknownHostException, IOException { // 设置服务器接收消息的端口 ServerSocket serverSocket =new ServerSocket(6379); // 创建服务器的socket对象 Socket soc= serverSocket.accept(); // 获取socket的输入流 InputStream in=soc.getInputStream(); byte[] arr=new byte[2048]; // 把获取到消息写进byte数组 in.read(arr); System.out.println(new String(arr)); serverSocket.close(); in.close(); } }
启动消息接收方此时消息接收方处于阻塞状态等待消息接收
import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; /** * 消息发送方 * @author BHL-lang * */ public class SocketSendTest { public static void main(String[] args) throws UnknownHostException, IOException { // 设置发送消息的地址和端口 Socket soc =new Socket("127.0.0.1",6379); // 获取socket的输出流 OutputStream ops=soc.getOutputStream(); // 通过输出流输出信息 ops.write(‘3‘); ops.flush(); ops.close(); soc.close(); } }
随后通过运行此类发送消息可以看到接收方在控制台打印的消息
原文:https://blog.51cto.com/u_15162069/2913177