Java 监听指定端口 并接收服务端传递的消息

1.简单介绍

 今天对接海康人脸识别时,需要指定端口实时监听人脸对比报警接收服务器推送的消息,所以查找资料总结如下:

  • 守护进程,和main方法运行,也可以通过listener监听方式 启动项目监听

 

public class SokectThread implements Runnable {	
	private BufferedReader reader;
	private Socket socket;
	//通过构造方法传递Socket  
	public SokectThread(Socket clientSocket)
	{
		try
		{
			// 得到socket连接
			socket = clientSocket;
			// 得到客户端发来的消息
			InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
			reader = new BufferedReader(isReader);
			// 清空socket缓冲区数据
			OutputStream os = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(os);
			String ms = "********************";
			pw.write(ms);
			pw.flush();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		String messages;
		try
		{
			while ((messages = reader.readLine()) != null)
			{
				System.out.println("客户端请求的消息: " + messages);
			}
		} catch (IOException e){
			e.printStackTrace();
		}

	}

}
  • 守护子线程,打印输出客户端消息

 

public class SokectThread implements Runnable {	
	private BufferedReader reader;
	private Socket socket;
	//通过构造方法传递Socket  
	public SokectThread(Socket clientSocket)
	{
		try
		{
			// 得到socket连接
			socket = clientSocket;
			// 得到客户端发来的消息
			InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
			reader = new BufferedReader(isReader);
			// 清空socket缓冲区数据
			OutputStream os = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(os);
			String ms = "********************";
			pw.write(ms);
			pw.flush();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		String messages;
		try
		{
			while ((messages = reader.readLine()) != null)
			{
				System.out.println("客户端请求的消息: " + messages);
			}
		} catch (IOException e){
			e.printStackTrace();
		}

	}

}

以上为个人总结,希望可以帮助有需要的你们!

你可能感兴趣的:(java)