package com.code.modules.roaddiseasecontroller; import com.alibaba.fastjson.JSON; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.*; public class TCP { private PrintWriter writer; // 声明PrintWriter类对象 Socket socket; // 声明Socket对象 private void client() { // 连接套接字方法 System.out.println("尝试连接 "); // 输出提示信息 DataInputStream dataInputStream = null; DataOutputStream dataOutputStream = null; String ip="117.184.126.50"; // String ip="10.17.18.122"; String charsetName = "gbk"; try { // 捕捉异常 socket = new Socket(ip, 8009); // 实例化Socket对象,连接端口8080服务器 writer = new PrintWriter(socket.getOutputStream(), true);//建立通信通道,强行输出数据 System.out.println("完成连接"); //发送数据 dataOutputStream = new DataOutputStream(socket.getOutputStream()); Map map = new HashMap(); Map iddr = new HashMap(); Map action = new HashMap(); action.put("reqid","1234 再来一次"); action.put("method","GEOCODER"); action.put("stime","2020-05-15T08:00:00"); action.put("location","121.672272,31.271923"); action.put("coordsys","gps"); action.put("management","pudong-gl"); iddr.put("action",action); map.put("iddr",iddr); String message =JSON.toJSONString(map); // message = "要发送的数据===我是客户端"; dataOutputStream.write(message.getBytes(charsetName)); //接收服务端的数据 StringBuilder stringBuilder = new StringBuilder(); dataInputStream = new DataInputStream(socket.getInputStream()); byte[] buf = new byte[1024]; int len = dataInputStream.read(buf); if (len != -1) { stringBuilder.append(new String(buf, 0, len,charsetName)); } dataInputStream.close(); dataOutputStream.close(); String receiveMessage = "" + stringBuilder; System.out.println("接收服务端发送的消息为:" + receiveMessage); } catch (IOException e){ e.printStackTrace(); }finally { try { if (dataOutputStream!=null){ dataOutputStream.close(); } if (dataInputStream!=null){ dataInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { // 主方法 TCP clien = new TCP(); // 创建本例对象 clien.client(); // 调用连接方法 // times(0); } public static void times(int count){ /** * Timer:是一个定时器工具,用来执行指定任务 * TimerTask:是一个抽象类,他的子类可以代表一个被Timer计划的任务 */ TimerTask task = new TimerTask() { @Override public void run() { // task to run goes here // 执行的输出的内容 if(count>5){ System.out.println(count); }else{ System.out.println("结束"); return; } } }; Timer timer = new Timer(); // 定义开始等待时间 --- 等待 5 秒 // 1000ms = 1s long delay = 5000; // 定义每次执行的间隔时间 long intevalPeriod = 5 * 1000; // schedules the task to be run in an interval // 安排任务在一段时间内运行 timer.scheduleAtFixedRate(task, delay, intevalPeriod); } }