通过ip,端口,连接服务器,得到内容:
public class TcpData {
public static String IP=null;
public static int PORT=0;
public static Integer temp=0;
public static void getData(){
new DataBase().exeSQL2();
System.out.println("地址为:"+IP+"----端口号为:"+PORT);
String hostname = IP;
int port = PORT;
String content = "{\"type\":\"identify\",\"istation\":\"-1\"}";
String result="";
PrintWriter out = null;
BufferedReader in = null;
try {
Socket socket = new Socket();
//socket链接指定的主机,超过10秒抛出链接不上异常
socket.connect(new InetSocketAddress(hostname,port), 10000);
// 得到请求的输出流对象
out = new PrintWriter(socket.getOutputStream());
// 发送请求参数
out.print(content);
// flush输出流的缓冲
out.flush();
// 定义 BufferedReader输入流来读取URL的响应
/*in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
String line;
System.out.println("-------------------");
char[] chars = new char[5];
System.out.println(in.readLine());
System.out.println("-------------------");
while ((line = in.readLine()) != null) {
result = line;
System.out.println("获取的结果为:"+result);
JsonUtils jsonUtils = new JsonUtils();
// jsonUtils.parseMap(result);
}*/
Reader reader = new InputStreamReader(socket.getInputStream(),"UTF-8");
char[] chars = new char[1024];
int len;
StringBuilder sb = new StringBuilder();
System.out.println("长度为:"+reader.read(chars));
while ((len=reader.read(chars)) != -1) {
sb.append(new String(chars, 0, len));
System.out.println("获取的结果为:"+sb);
JsonUtils jsonUtils = new JsonUtils();
//此为数据解析方法,单独运行该Java文件测试连通性时,可以注释掉该代码
result = sb.toString();
jsonUtils.parseMap(result);
sb.setLength(0);
}
temp = 1;
System.out.println("终止发送,程序持续访问Socket连接");
}
catch(Exception ex) {
System.out.println("发送 POST 请求出现异常!"+ex);
System.out.println("终止发送,程序持续访问Socket连接");
temp = 1;
}
finally {
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
if (temp==1) {
new TcpData().getData();
}
}
}
public static void main(String[] args) {
System.out.println("--");
TcpData.getData();
}
}
对接收的内容进行解析:json字符串转Map
public static Map<String, Object> parseMap(String jsonStr) throws IOException, ParseException {
Map<String, Object> map = objectMapper.readValue(jsonStr, Map.class);
System.out.pri
通过socket接收报警信息,存入数据库
最新推荐文章于 2023-01-29 11:52:50 发布
这段代码展示了如何用Java实现通过TCP socket连接服务器,接收报警信息,然后将接收到的JSON数据解析成Map并存入数据库。程序首先创建Socket连接,发送请求并读取响应。接收到的数据经过解析后,根据字段提取关键信息,并存储到Evr_Alarm表中。
摘要由CSDN通过智能技术生成