Socket发送消息小demo

我总是喜欢搞一个特别小的demo。反正看的不深,就是能发送和接受,然后其中也有一定的优化。以下就是代码喽:

package com.hxkj.scoket;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import com.hxkj.utils.NewSftpUtils;

public class ListenAgent {

	public void listenSocket() {
		try {
			System.setOut(new PrintStream(new FileOutputStream("D:/makepic/listen_out.txt")));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(1578);
			JSONObject jsonJob = null;
			Socket socket = null;
			InputStream is = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			String str = null;
			String mark = "";
			while (true) {
				System.out.println("开始等待端口1578的连接....");
				socket = serverSocket.accept();
				is = socket.getInputStream();
				isr = new InputStreamReader(is);
				br = new BufferedReader(isr);
				// String str =null,info="";
				String info = "";
				while ((str = br.readLine()) != null) {
					info += str;
				}
				System.out.println("接受到的信息为:" + info);
				if (info.contains("heartbeat")) {
					System.out.println("心跳");
					continue;
				}
				jsonJob = new JSONObject(info);
				if (jsonJob == null || jsonJob.length() == 0) {
					continue;
				}
				socket.shutdownInput();
				br.close();
				isr.close();
				is.close();
				socket.close();
				// 设置数据源为oracle
				mark = jsonJob.getString("mark");
				switch (mark) {
				case "heartbeat":
					// System.out.println("真的心跳了吗");
					break;
				case "makePic":

					makePic(jsonJob);
					break;
				default:
					break;
				}
				// 执行

			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// listenSocket();

		}
	}

	private void makePic(JSONObject jo) {
		String picType = jo.getString("picType");
		String number = jo.getString("number");
		String provinceId = jo.getString("provinceId");
		String level = jo.getString("level");

		String workPath = "D:/code/";
		if ("county".equals(level)) {
			workPath = workPath + "xian";// _tudi.py
		} else if ("city".equals(level)) {
			workPath = workPath + "shi";
		}
		if ("land".equals(picType)) {
			workPath += "_tudi.py ";
		} else if ("country".equals(picType)) {
			workPath += "_station_guojia.py ";
		} else if ("country_area".equals(picType)) {
			workPath += "_station_quyu.py ";
		} else if ("administrative".equals(picType)) {
			workPath += "_xingzheng.py ";
		}

		String cmd = "python " + workPath + " " + number + " " + provinceId;
		System.out.println("执行的命令为:" + cmd);
		ExecuteShell ec = new ExecuteShell(cmd);
		ec.run();
		String error = ec.getError();
		if (error != null && error.length() != 0) {
			System.out.println("错误日志为:" + error);
		}

		String outPath = "D:/result_img/";// tudi/
		if ("land".equals(picType)) {
			outPath += "tudi/";
		} else if ("country".equals(picType)) {
			outPath += "station/guojia/";
		} else if ("country_area".equals(picType)) {
			outPath += "station/quyu/";
		} else if ("administrative".equals(picType)) {
			outPath += "xingzheng/";
		}

		File file = new File(outPath + number + "_.jpg");

		System.out.println("生成的文件为:" + file.getAbsolutePath());
		int i = 0;

		while (!file.exists()) {
			if (i >= 85) {
				System.out.println("数据超时");
				return;
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			i++;

		}

		NewSftpUtils newSftp = new NewSftpUtils("上传的目标ip", 端口, "账户", "密码");
		String path = "/home/climatesign/out/jpg/batch/" + picType;
		System.out.println("目标路径为:" + path + ",文件为:" + file.getAbsolutePath());
		newSftp.upload(path, file);

	}

	public void sendInfo(String ip, String message, String mark) {
		Socket socket = null;
		OutputStream os = null;
		PrintWriter pw = null;
		try {
			socket = new Socket(ip, 1578);
			os = socket.getOutputStream();// 字节输出流
			pw = new PrintWriter(os);// 将输出流包装成打印流
			String json = "";
			json = "{\"mark\":\"" + mark + "\"," + message + "}";
			System.out.println("发送过去的:" + json);
			pw.write(json);
			pw.flush();
			socket.shutdownOutput();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (pw != null) {
					pw.close();
				}
				if (os != null) {
					os.close();
				}
				if (socket != null) {
					socket.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	

	public void heartbeat() {
		long delay = 0;
		long intevalPeriod = 60 * 1000 * 9;
		final Timer timer = new Timer();

		TimerTask timerTask = new TimerTask() {

			@Override
			public void run() {
				sendInfo("127.0.0.1", "{}", "heartbeat");
			}

		};
		timer.schedule(timerTask, delay, intevalPeriod);
	}

	public static void main(String[] args) {

		System.out.println(Thread.currentThread().getName());
		final ListenAgent listenAgent = new ListenAgent();
		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName());
				listenAgent.listenSocket();

			}
		}).start();
		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName());
				listenAgent.heartbeat();

			}
		}).start();
	}

	public void start() {
		System.out.println(Thread.currentThread().getName());
		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName());
				listenSocket();

			}
		}).start();
		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName());
				heartbeat();

			}
		}).start();
	}
}

接下来,我们分析一下,这个本来是打成一个jar包,相当于一个监听程序一样。里面有主方法。

第一,首先找到主方法,里面是两个线程,都是什么内容呢,第一个线程,是启动了这个服务端的socket服务,listenSocket()这个方法中

为什么要有心跳检测,下面会讲

接下来就是业务逻辑了。

 

第二,为什么要有心跳检测,程序员先辈们在做socket网络通讯传输的时候,会有一个机制,就是长时间不用的socket,自动就给关闭了,现在可以根据我们自己的业务,不让他关闭,所以在下面,我开了一个定时任务(也就是main方法中开的第二个线程)

这个定时任务就是心跳检测,没有人给服务端的socket发送信息的时候,我们就让它自己给自己发送着玩!也就不让他自动关闭!

然后把这个打一个jar包*(记得写上自己的业务逻辑哦),接下来就是测试了!

方法也很简单,写一个发送者(生产者)

测试成功!

打完,收工!!!

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本系统的研发具有重大的意义,在安全性方面,用户使用浏览器访问网站时,采用注册和密码等相关的保护措施,提高系统的可靠性,维护用户的个人信息和财产的安全。在方便性方面,促进了校园失物招领网站的信息化建设,极大的方便了相关的工作人员对校园失物招领网站信息进行管理。 本系统主要通过使用Java语言编码设计系统功能,MySQL数据库管理数据,AJAX技术设计简洁的、友好的网址页面,然后在IDEA开发平台中,编写相关的Java代码文件,接着通过连接语言完成与数据库的搭建工作,再通过平台提供的Tomcat插件完成信息的交互,最后在浏览器中打开系统网址便可使用本系统。本系统的使用角色可以被分为用户和管理员,用户具有注册、查看信息、留言信息等功能,管理员具有修改用户信息,发布寻物启事等功能。 管理员可以选择任一浏览器打开网址,输入信息无误后,以管理员的身份行使相关的管理权限。管理员可以通过选择失物招领管理,管理相关的失物招领信息记录,比如进行查看失物招领信息标题,修改失物招领信息来源等操作。管理员可以通过选择公告管理,管理相关的公告信息记录,比如进行查看公告详情,删除错误的公告信息,发布公告等操作。管理员可以通过选择公告类型管理,管理相关的公告类型信息,比如查看所有公告类型,删除无用公告类型,修改公告类型,添加公告类型等操作。寻物启事管理页面,此页面提供给管理员的功能有:新增寻物启事,修改寻物启事,删除寻物启事。物品类型管理页面,此页面提供给管理员的功能有:新增物品类型,修改物品类型,删除物品类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值