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

    测试效果:

  • 相关阅读:
    Hibernatede 一对多映射配置
    Hibrenate之事务的理解以及代码编写
    The servlet name already exists.解决方法
    hibernate入门程序
    什么是orm思想?
    Java的MVC模式简介
    JAVA框架之Hibernate框架的学习步骤
    java常见命名规则
    解决get方法提交参数中文乱码问题:
    谈谈对Spring IOC(控制反转)的理解--转
  • 原文地址:https://www.cnblogs.com/zhouheblog/p/10668723.html
Copyright © 2011-2022 走看看