标签:ring mil click one soc package 数据 关闭 main
socket :网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一段称为一个socket
socket通信示例:
1 package pers.example.demo.socket; 2 3 import java.io.InputStream; 4 import java.net.ServerSocket; 5 import java.net.Socket; 6 7 public class SocketTest { 8 public static void main(String[] args) { 9 10 try { 11 int port = 55555; 12 ServerSocket serverSocket = new ServerSocket(port); 13 Socket socket = serverSocket.accept(); 14 InputStream inputStream = socket.getInputStream(); 15 byte[] bytes = new byte[1024]; 16 int len; 17 System.out.println("等待连接中。。。"); 18 StringBuilder sb = new StringBuilder(); 19 while ((len = inputStream.read(bytes)) != -1) { 20 sb.append(new String(bytes, 0, len, "UTF-8")); 21 } 22 System.out.println("接收到输入值:"); 23 System.out.println(sb); 24 inputStream.close(); 25 socket.close(); 26 serverSocket.close(); 27 28 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } 32 } 33 34 }
1 package pers.example.demo.socket; 2 3 import java.io.IOException; 4 import java.io.OutputStream; 5 import java.net.Socket; 6 7 public class SocketClientTest { 8 public static void main(String[] args) { 9 try { 10 Socket socket = new Socket("127.0.0.1",55555); 11 OutputStream outputStream = socket.getOutputStream(); 12 outputStream.write("输入流".getBytes("UTF-8")); 13 outputStream.close(); 14 socket.close(); 15 } catch (IOException e) { 16 e.printStackTrace(); 17 } 18 19 20 } 21 }
socket可通过socket.shutdownOutput();和socket.shutdownInput()方法关闭输入输出流,直接调用流的close方法会直接关闭socket
标签:ring mil click one soc package 数据 关闭 main
原文地址:https://www.cnblogs.com/gwxHome/p/10747374.html