配置外部接口 用于查询某市的公交线路,先注册再申请api,体验用户每天可以查询50次总时长一个月。
更改代码,把BusService里的URL换成自己申请的URL
http://apis.haoservice.com/lifeservice/busline/stopname?key=自己的id&city=自己要查询的城市名&keywords=站名
http://apis.haoservice.com/lifeservice/busline/stopname?key=自己的id&city=自己要查询的城市名&keywords=线路
导入fastjosn的包 https://mvnrepository.com/artifact/com.alibaba/fastjson版本随意
素材 bus图片
保证项目目录和素材名称跟图片一致
先启动BusService,再启动RandomService,最后启动BusClient
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
public class BusClient extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Pane root = new Pane();
//第一行导航栏
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.setAlignment(Pos.CENTER);
TextArea textArea = new TextArea();
textArea.setPrefRowCount(1);//输入框行数
textArea.setPromptText("1查询线路,2查询行驶");
textArea.setPrefWidth(300);
Button query = new Button("查询");
query.setPrefHeight(50);
query.setPrefWidth(80);
query.setCursor(Cursor.HAND);
query.setBackground(new Background(new BackgroundFill(Color.CORAL, new CornerRadii(20), new Insets(3))));;
Text tip = new Text();
hBox.getChildren().addAll(textArea,query,tip);
//到站渲染
Pane site = new Pane();
//线路查询显示/站点查询显示
Pane way = new Pane();
way.setLayoutY(30);
query.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
way.getChildren().clear();
site.getChildren().clear();
String[] strings = textArea.getText().split("\n");
String first = strings[0].replace(" ","");//功能
System.out.println("功能:"+first);
if(strings.length==1){
tip.setText("请用回车间隔");
return;
}
String second = strings[1].replace(" ","");;//公交号/站点名称
System.out.println("输入:"+second);
if(!"1".equals(first)&&!"2".equals(first)&&!"3".equals(first)){
tip.setText("请输入1或2或3");
return;
}else
tip.setText("查询成功");
try {
if("3".equals(first)){
ArrayList<String> ways = socket(1, second);//先渲染路线
paintWay(way,ways,1,tip);
ArrayList<String> sites = socket(3, second);//加载到站信息
paintSite(site,sites,tip);
}
else{
ArrayList<String> list = socket(Integer.parseInt(first), second);
paintWay(way,list,Integer.parseInt(first),tip);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
root.getChildren().addAll(hBox,site,way);
Scene sc = new Scene(root,560,400);
primaryStage.setScene(sc);
primaryStage.show();
}
private void paintSite(Pane pane,ArrayList<String> list,Text tip) {
for(String str:list){
if("err".equals(str)){
tip.setText("无此公交线路");
return;
}
int index = Integer.parseInt(str);
System.out.println("站点"+index);
//相对路径
Image image = new Image("bus.png");
ImageView view = new ImageView();
view.setImage(image);
view.setFitHeight(15);
view.setFitWidth(15);
view.setLayoutX(20+index*20);
view.setLayoutY(60);
pane.getChildren().add(view);
}
}
private ArrayList<String> socket(int kind,String way) throws IOException{
ArrayList<String> list = new ArrayList<>();
Socket socket = new Socket("localhost",9200);
PrintStream outputStream = new PrintStream(socket.getOutputStream());
outputStream.println(kind);
outputStream.println(way);
Scanner sc = new Scanner(socket.getInputStream());
while (sc.hasNext()){
list.add(sc.next());
}
socket.close();
return list;
}
private void paintWay(Pane pane,ArrayList<String> list,int kind,Text tip){
int i = 0;
for (String str:list) {
if(str.equals("err")){
if(kind==1)
tip.setText("无此公交线路");
else
tip.setText("无此站台");
} else if(kind==1){
Text text = new Text(str);
Text digit = new Text(String.valueOf(i+1));
digit.setLayoutX(20+i*20);
digit.setLayoutY(80);
text.setWrappingWidth(20);
text.setLayoutX(20+i*20);
text.setLayoutY(140);
text.setFill(Color.BLUE);
Line line = new Line(20+i*20,100,40+i*20,100);
line.setStroke(Color.RED);
line.setLayoutY(5);
Circle circle = new Circle(30+i*20,100,5);
circle.setLayoutY(5);
circle.setFill(Color.RED);
pane.getChildren().addAll(digit,line,circle,text);
}else if(kind==2){
Text text = new Text("线路"+(i+1)+":"+str);
text.setLayoutX(20);
text.setLayoutY(50+i*25);
pane.getChildren().add(text);
}
i++;
}
}
public static void main(String[] args) {
launch(args);
}
}
public class BusLine {
private String start_stop;
private String end_stop;
private String id;
private String name;
private String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.io.PrintStream;
import java.net.*;
import java.util.*;
public class BusService {
static Map<String,List<String>> map = new HashMap<>();
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(9200);
while (true) {
Socket accept = server.accept();
Scanner inputStream = new Scanner(accept.getInputStream());
PrintStream outputStream = new PrintStream(accept.getOutputStream());
new Thread(() -> {
int kind = inputStream.nextInt();
String way = inputStream.next();
outputStream.print(getKind(kind, way));
outputStream.close();
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
private static String getKind(int kind, String way) {
StringBuffer stringBuffer = new StringBuffer();
List<String> list = null;
System.out.println(map);
if(map.containsKey(way+kind)){
list = map.get(way+kind);
}else {
try {
if (kind == 1) {
list = getWay(way);
} else if(kind==2){
list = getDriver(way);
}else {
return udp(way);
}
} catch (Exception e) {
e.printStackTrace();
}
map.put(way+kind,list);
}
if(list==null)
return "err";
for (int i = 0; i < list.size(); i++) {
stringBuffer.append(list.get(i)).append("\n");
}
return stringBuffer.toString();
}
public static String udp(String way) throws Exception{
List<String> ways = map.get(way + 1);
if(ways==null)
return "err";
DatagramSocket socket = new DatagramSocket(9400);
byte[] sendBytes = String.valueOf(ways.size()).getBytes();
DatagramPacket sendData = new DatagramPacket(sendBytes,0,sendBytes.length,InetAddress.getLocalHost(),9300);
socket.send(sendData);
byte[] receiveBytes = new byte[1024];
DatagramPacket receiveData = new DatagramPacket(receiveBytes,receiveBytes.length);
socket.receive(receiveData);
socket.close();
return new String(receiveData.getData(),0,receiveData.getLength());
}
private static List<String> getDriver(String way) throws IOException {
List<String> list = new ArrayList<>();//经过此站的公交车车名
URL url = new URL("http://apis.haoservice.com/lifeservice/busline/stopname?key=1a908ae9504444009a40dff12259776c&city=南昌&keywords=" + way);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
Scanner scanner = new Scanner(conn.getInputStream());
String ways = scanner.nextLine();
if (ways.length() < 250)
return null;
String buslines = ways.substring(ways.indexOf("buslines") + 10, ways.indexOf("citycode") - 2);
List<BusLine> busLines = JSON.parseArray(buslines, BusLine.class);
for (int i = 0; i < busLines.size(); i++) {
list.add(busLines.get(i).getName());
}
return list;
}
public static List<String> getWay(String way) throws IOException {
System.out.println("查询线路");
List<String> list = new ArrayList<>();//查询当前公交的线路
URL url = new URL("http://apis.haoservice.com/lifeservice/busline/linename?key=1a908ae9504444009a40dff12259776c&city=南昌&keywords=" + way);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
Scanner scanner = new Scanner(conn.getInputStream());
String ways = scanner.nextLine();
if (ways.length() < 250)
return null;
String busstops = ways.substring(ways.lastIndexOf("busstops") + 10, ways.length() - 4);
List<BusStop> busStops = JSON.parseArray(busstops, BusStop.class);
for (int i = 0; i < busStops.size(); i++) {
list.add(busStops.get(i).getName());
}
return list;
}
}
public class BusStop {
private String sequence;
private String id;
private String name;
private String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Random;
public class RandomService {
public static void main(String[] args) throws IOException {
StringBuffer buffer = new StringBuffer();
Random random = new Random();
DatagramSocket socket = new DatagramSocket(9300);
byte[] receiveBytes = new byte[1024];
while (true){
DatagramPacket receiveData = new DatagramPacket(receiveBytes,receiveBytes.length);
socket.receive(receiveData);
String s = new String(receiveData.getData(), 0, receiveData.getLength());
int size = Integer.parseInt(s);
//当size为0时防止报错
if(size==0)
size=3;
for (int i = 0; i < random.nextInt(size/3); i++) {
buffer.append(random.nextInt(size)+"\n");
}
System.out.println("随机数:"+buffer.toString());
byte[] sendBytes = buffer.toString().getBytes();
DatagramPacket sendData = new DatagramPacket(sendBytes,0,sendBytes.length, InetAddress.getLocalHost(),9400);
socket.send(sendData);
buffer.setLength(0);
}
}
}