• Socket通信


    项目需求java客户端与C++服务端进行通信,本人对这方面是小白一枚,经过多天查资料,整理了一点,特贴出来,万一哪天用到了,回来瞅一眼,代码如下:

    public static final String IP_ADDR = "127.0.0.1";//服务器地址
    public static final int PORT = 4999;//服务器端口号
    private static DataOutputStream outStr = null;
    private static InputStream inStr = null;

    public AjaxJson socketMsg() throws IOException {
    AjaxJson ajaxJson = new AjaxJson();
    // String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
    String str = "abc";
    Socket socket = null;
    try {
    //创建一个流套接字并将其连接到指定主机上的指定端口号
    socket = new Socket(IP_ADDR, PORT);
    //读取服务器端数据
    // DataInputStream input = new DataInputStream(socket.getInputStream());
    inStr = socket.getInputStream();
    //向服务器端发送数据
    outStr = new DataOutputStream(socket.getOutputStream());
    outStr.writeUTF(str);
    // String ret = input.readUTF();
    byte[] b = new byte[1024];
    int r = inStr.read(b);
    String ret = "";
    if (r > -1) {
    ret = new String(b);
    System.out.println("服务器端返回过来的是: " + ret);
    System.out.println("客户端将关闭连接");
    ajaxJson.setMsg("请求成功");
    ajaxJson.setSuccess(true);

    }

    } catch (Exception e) {
    System.out.println("客户端异常:" + e.getMessage());
    ajaxJson.setMsg("服务器异常");
    ajaxJson.setSuccess(false);
    }finally {
    outStr.close();
    inStr.close();
    socket.close();
    }
    return ajaxJson;
    }
  • 相关阅读:
    MySQL 修改数据
    Scala 简介
    tensorflow mnist read_data_sets fails
    Mac安装Homebrew
    MySQL 创建数据表
    MySQL 数据类型
    wc--Linux
    xxx is not in the sudoers file.This incident will be reported.的解决方法
    linux centos下安装dokuwiki
    CentOS修改系统时间
  • 原文地址:https://www.cnblogs.com/leirenyuan/p/7473827.html
Copyright © 2020-2023  润新知