php 不依赖第三方服务与 java 后台服务通信

服务端 java 监听端口

package com.st.xk;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class XKServer {

	private static boolean isDo = true;

	public static void main(String[] args) {
		try {
			ServerSocket ss = new ServerSocket(8090, 10, InetAddress.getByName("172.16.2.8"));
			while (isDo) {
				Socket s = ss.accept();
				new WorkerThread(s).start();
			}
			ss.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Runtime.getRuntime().addShutdownHook(new Thread(){
			public void run(){
				isDo = false;
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}

}
package com.st.xk;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class WorkerThread extends Thread {

	private Socket socket;

	public WorkerThread(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			
			StringBuilder sb = new StringBuilder();
			String str;
			while((str = reader.readLine()) != null){
				sb.append(str);
			}
			socket.shutdownInput();
			
			writer.write(sb.toString());
			writer.flush();
			socket.shutdownOutput();
			
			reader.close();
			writer.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

客户端 php 利用 socket 连接向 java 程序发送消息

< ?php
function testSocket($i){
	$str = '{id:'.$i.',time:'.time().'}';
	$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	socket_connect($socket, '172.16.2.8', 8090);
	socket_write($socket, $str, strlen($str));
	socket_shutdown($socket, 1);
	while($rStr = socket_read($socket, 4096)){
		echo $rStr;
	}
	echo "\n";
	socket_close($socket);
}
?>

发表评论

电子邮件地址不会被公开。 必填项已用*标注