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

    测试效果:

  • 相关阅读:
    Scrapy框架基础使用
    python爬虫练习--爬取今日头条街拍图片
    python爬虫练习--爬取所有微博
    python爬虫练习--爬取猫眼热映口碑榜
    python练习---校园管理系统
    python爬虫练习--爬取猫眼top100电影信息
    基础篇-Python的urllib库
    1--爬虫环境安装篇
    Confluence 如何查看页面 ID
    导入 Gradle 项目到 IntelliJ IDEA
  • 原文地址:https://www.cnblogs.com/zhouheblog/p/10668723.html
Copyright © 2011-2022 走看看