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
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值