1.UDP
面向无连接,数据不安全,速度快。不区分客户端与服务端。
使用udp的简单小例子:
- 接收端Receive
- DatagramSocket socket = new DatagramSocket(6666); //创建socket
- DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); //创建packet
-
- while(true) {
- socket.receive(packet); //接收货物
- byte[] arr = packet.getData();
- int len = packet.getLength();
- String ip = packet.getAddress().getHostAddress();
- System.out.println(ip + ":" + new String(arr,0,len));
- }
- 发送端Send
- DatagramSocket socket = new DatagramSocket(); //创建socket相
- Scanner sc = new Scanner(System.in);
-
- while(true) {
- String str = sc.nextLine();
- if("quit".equals(str))
- break;
- DatagramPacket packet = //创建packet
- new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
- socket.send(packet);
- }
- socket.close();
复制代码
TCP
面向连接(三次握手),数据安全,速度略低。分为客户端和服务端。
三次握手: 客户端先向服务端发起请求, 服务端响应请求, 传输数据 注意,开启线程是先开启服务器,在不重新运行程序的情况下只能开启一次
tcp的小例子- ServerSocket server = new ServerSocket(9999); //创建服务器
- while(true) {
- final Socket socket = server.accept(); //接受客户端的请求
- new Thread() {
- public void run() {
- try {
- BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- PrintStream ps = new PrintStream(socket.getOutputStream());
- ps.println("欢迎访问客户端");
- System.out.println(br.readLine());
- ps.println("欢迎再次访问");
- System.out.println(br.readLine());
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }.start();
- }
- }
复制代码- Socket socket = new Socket("127.0.0.1", 9999); //创建Socket指定ip地址和端口号
- InputStream is = socket.getInputStream(); //获取输入流
- OutputStream os = socket.getOutputStream(); //获取输出流
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
- PrintStream ps = new PrintStream(os);
-
- System.out.println(br.readLine());
- ps.println("访问服务器啦");
- System.out.println(br.readLine());
- ps.println("再次访问服务器啦");
- socket.close();
复制代码
|
|