zoukankan      html  css  js  c++  java
  • Java Socket 服务端发送数据 客户端接收数据

    服务端:

    package com.thinkgem.wlw.modules.api.test.socket;
    
    /**
     * @Author: zhouhe
     * @Date: 2019/4/8 9:30
     */
    
    import java.io.*;
    import java.net.*;
    
    /**
     * 服务端
     * 负责发送数据
     */
    public class SocketServerTest {
    
        private static final int PORT = 5209;
    
    
        public static void test() {
            ServerSocket server = null;
            Socket socket = null;
            DataOutputStream out = null;
            try {
                server = new ServerSocket(PORT);
                socket = server.accept();
                out = new DataOutputStream(socket.getOutputStream());
                while (true) {
                    Thread.sleep(1000);
                    out.writeUTF(getRandomStr());
                    out.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
        private static String getRandomStr() {
            String str = "";
            int ID = (int) (Math.random() * 30);
            int x = (int) (Math.random() * 200);
            int y = (int) (Math.random() * 300);
            int z = (int) (Math.random() * 10);
            str = "ID:" + ID + "/x:" + x + "/y:" + y + "/z:" + z;
            return str;
        }
    
    
        public static void main(String[] args) {
            test();
        }
    }

    客户端:

    package com.thinkgem.wlw.modules.api.test.socket;
    
    /**
     * @Author: zhouhe
     * @Date: 2019/4/8 9:27
     */
    
    import java.net.*;
    import java.io.*;
    
    /**
     * 客户端
     * 负责接收数据
     */
    public class SocketClientTest {
        private static final String HOST = "127.0.0.1";
        private static final int PORT = 5209;
    
        private static void test() {
            Socket socket = null;
            DataInputStream dis = null;
            InputStream is = null;
    
            try {
                socket = new Socket(HOST, PORT);
                is = socket.getInputStream();
                dis = new DataInputStream(is);
                while (true) {
                    System.out.println("receive_msg:" + dis.readUTF());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
    
            test();
        }
    }

    测试效果:

  • 相关阅读:
    什么是看板方法?
    瓶颈法则
    累积流图——你还没有用过吗?
    为什么我们关注看板方法?
    蒟蒻报道
    博客更换通知
    浅谈树套树(线段树套平衡树)&学习笔记
    浅谈FFT(快速博立叶变换)&学习笔记
    题解 洛谷P1903/BZOJ2120【[国家集训队]数颜色 / 维护队列】
    题解 洛谷P4550/BZOJ1426 【收集邮票】
  • 原文地址:https://www.cnblogs.com/zhouheblog/p/10668723.html
Copyright © 2011-2022 走看看