• 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();
        }
    }

    测试效果:

  • 相关阅读:
    java开发异常类型汇总
    dm642在线写EPROM.txt
    [Codecademy] HTML&CSS 第一课:HTML Basic
    bram和dram差别
    Advanced Fruits HDU杭电1503【LCS的保存】
    add Admob with Cocos2d-x on iOS
    一种基于Qt的可伸缩的全异步C/S架构server实现(五) 单层无中心集群
    【SSH2框架(理论篇)】--SSH2 Vs 经典三层
    CSS BFC学习笔记
    【智能家居篇】wifi网络结构(上)
  • 原文地址:https://www.cnblogs.com/zhouheblog/p/10668723.html
Copyright © 2020-2023  润新知