码迷,mamicode.com
首页 > 其他好文 > 详细

Socket

时间:2020-04-24 22:05:14      阅读:80      评论:0      收藏:0      [点我收藏+]

标签: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 }
View Code
技术图片
 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 }
View Code

 socket可通过socket.shutdownOutput();和socket.shutdownInput()方法关闭输入输出流,直接调用流的close方法会直接关闭socket

Socket

标签:ring   mil   click   one   soc   package   数据   关闭   main   

原文地址:https://www.cnblogs.com/gwxHome/p/10747374.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!