动态航班信息处理的java实现(源码)

EchoClient:

 

import java.net.*;
import java.nio.channels.*;
import java.nio.*;
import java.io.*;
import java.nio.charset.*;
import java.util.*;
public class EchoClient86
{
  private DatagramChannel datagramChannel = null;
  private ByteBuffer sendBuffer=ByteBuffer.allocate(1024);
  private ByteBuffer receiveBuffer=ByteBuffer.allocate(1024);
  private Charset charset=Charset.forName("GBK");
  private Selector selector;
  
  public EchoClient86()throws IOException{
    this(7000);
  }
  public EchoClient86(int port)throws IOException{
    datagramChannel = DatagramChannel.open();
    InetAddress ia = InetAddress.getLocalHost();
    InetSocketAddress isa = new InetSocketAddress(ia,port);
    datagramChannel.configureBlocking(false); //设置为非阻塞模式
    datagramChannel.socket().bind(isa); //与本地地址绑定
    isa = new InetSocketAddress(ia,9999);
    datagramChannel.connect(isa); //与远程地址连接
    selector=Selector.open();
  }
  public static void main(String args[])throws IOException
  {
    int port=7000;
    if(args.length>0)port=Integer.parseInt(args[0]);    
    final EchoClient86 client=new EchoClient86(port);
    client.talk();
  }
  
  public void talk()throws IOException {
     datagramChannel.register(selector,
                          SelectionKey.OP_READ 
                        );
     while (selector.select() > 0 ){
       Set readyKeys = selector.selectedKeys();
       Iterator it = readyKeys.iterator();
       while (it.hasNext()){
         SelectionKey key=null;
         try{
             key = (SelectionKey) it.next();
             it.remove();
             if (key.isReadable()) {
                 receive(key);
             }
       
         }catch(IOException e){
            e.printStackTrace();
            try{
                if(key!=null){
                    key.cancel();
                    key.channel().close();
                }
            }catch(Exception ex){e.printStackTrace();}
         }
      }//#while
    }//#while
  }
  public void receive(SelectionKey key)throws IOException{
    DatagramChannel datagramChannel=(DatagramChannel)key.channel();
    datagramChannel.read(receiveBuffer);
    receiveBuffer.flip();
    String receiveData=decode(receiveBuffer);
    if(receiveData.indexOf("\n")==-1)
     return;
    String outputData=receiveData.substring(0,receiveData.indexOf("\n")+1);
    System.out.print(outputData);
    if(outputData.equals("no data!\r\n")){
        key.cancel();
        datagramChannel.close();
        System.out.println("关闭与服务器的连接");
        selector.close();
        System.exit(0);
    }
    ByteBuffer temp=encode(outputData);
    receiveBuffer.position(temp.limit());
    receiveBuffer.compact();
  }
  public String decode(ByteBuffer buffer){  //解码
    CharBuffer charBuffer= charset.decode(buffer);
    return charBuffer.toString();
  }
  public ByteBuffer encode(String str){  //编码
    return charset.encode(str);
  }
}

EchoServer:

import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Handler;

public class EchoServer9 {
    private static int port = 9999;           //端口号
    private ExecutorService executorService;  //线程池
    private final int POOL_SIZE = 4;          //单个CPU时线程池中工作线程的数量
    private BufferedReader br = null;         //用于存储数据
    private static int num = 0;               //记录数据
    private DatagramSocket datagramSocket;    //新建一个datagramSocket

    public EchoServer9() throws Exception {
        datagramSocket = new DatagramSocket(port);//建立datagramSocket并绑定端口
        executorService = 
        		Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
        //创建线程池;Runtime的availableProcessors()方法返回当前系统的CPU的数目
        br = new BufferedReader(new FileReader("fds_data(lab4).txt"));  //BufferedReader存储发送文件的内容
        sum();
        System.out.println("服务器启动");
    }
    public void sum() throws Exception {
        while(br.readLine() != null) {
            num++;
        }
    }
    public void service() throws Exception{
        while(true) {
            try {
                DatagramPacket packet = new DatagramPacket(new byte[512], 512);
                datagramSocket.receive(packet);    //接收来自任意一个客户端的数据报
                String msg = new String(packet.getData(), 0 , packet.getLength());
                System.out.println("接收到客户连接,来自:" + packet.getAddress() + ":" + packet.getPort() );
               
                packet.setData(("共有" + num + "条记录" + "\r\n").getBytes());
                datagramSocket.send(packet);                            //服务器回一个数据报
                executorService.execute(new Handlderer(packet));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws  Exception{
        InetAddress address = InetAddress.getLocalHost();  //获取当前IP
        System.out.println("服务器IP地址:" + address.getHostAddress() + "  端口:" + port);
        new EchoServer9().service();
    }
}
class Handlderer implements Runnable {//负责与用户通信
    DatagramPacket datagramPacket;
    DatagramSocket datagramSocket;

    public Handlderer(DatagramPacket datagramPacket) {
        try {
            datagramSocket = new DatagramSocket();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        this.datagramPacket = datagramPacket;
    }
    @Override
    public void run() {
        try {
            FileInputStream file = new FileInputStream("fds_data(lab4).txt");
            FileReader fr = new FileReader("fds_data(lab4).txt");
            BufferedReader buff=new BufferedReader(fr);
            String stg="00";
           // while ((stg = buff.readLine()) != "no data") {             //把数据读到字节数组中
            while (true) {
            	stg = buff.readLine();
                            	byte[] buffer = new byte[256];
            	buffer=stg.getBytes();
            	datagramPacket.setData(buffer);
                datagramSocket.send(datagramPacket);
                Thread.sleep(10);
                if(stg.contains("no data"))
                {
                	 stg="no data!";
                 	buffer=stg.getBytes();
                 	datagramPacket.setData(buffer);
                     datagramSocket.send(datagramPacket);
                     
                	datagramSocket.close();
                	fr.close();
                    buff.close();
                    break;
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }
}

Test:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.awt.Color;
 
public class EXtest9 extends JFrame {

	private JPanel contentPane;
	private JTable table;
	private DefaultTableModel tm;//创建model
	private JButton btnNewButton;
	private JButton btnNewButton_1;
	private int count=0;
	private ReceiveAndProcesData rece;
	static List list1=new ArrayList<>();//建立链表用于存储航班号
	static List list2=new ArrayList<>();//建立链表用于存储对应的柜台
	static List list=new ArrayList<>();
	int list22=0;
	int num=0;                                 
	static String z;//记录终到站
	static String  f_bdop;
	static String hkgs;//航空公司
	static String hbh;//航班号
	static String jtz;//经停站
	static String zdz;//终到站
	static String bpsj;//办票时间
	static String qfsj;//起飞时间
	static String djk="暂无";//登机口
	 String key1= "schd_none";
     String key2= "flop_ckop";
     String test="*等待更新*";
     
     private String remoteHost = "localhost";
     private int remotePort = 9999;
     private DatagramSocket socket;
     private Charset charset  = Charset.forName("UTF-8");
	/**
	 * Launch the application.
	 */
    /* public void setvalue(Object value,int row,int col)
     {
    	 data[row][col]=value;
    	 fireTableCellUpdated(row,col);
     }*/
	public static void main(String[] args) 
	{
		EventQueue.invokeLater(new Runnable() {//设置计算器可见
			public void run() {
				try {
					EXtest9 frame = new EXtest9();
					frame.setVisible(true);                        //设为可见
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}//main

	/**
	 * Create the frame.
	 * @throws IOException 
	 */
	public EXtest9() throws IOException {
		 socket = new DatagramSocket();
		setTitle("\u822A\u663E\u7EC8\u7AEF\u663E\u793A");             //显示标题
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);                               //设置位置
		contentPane = new JPanel();                                  //新建JPanel
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));          //设置边框
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);                                 //设为主面板
		
		JScrollPane scrollPane = new JScrollPane();                  //添加JScrollPane
		contentPane.add(scrollPane, BorderLayout.CENTER);
		
		table = new JTable();
		table.setBackground(Color.WHITE);
		tm = new DefaultTableModel(
				new Object[][] {
				},
				new String[] {
						//"\u884C\u53F7", "\u767B\u673A\u53E3", "\u8D77\u98DE\u65F6\u95F4", "\u529E\u7968\u65F6\u95F4", "\u7EC8\u5230\u7AD9", "\u7ECF\u505C\u7AD9", "\u822A\u7A7A\u516C\u53F8", "\u822A\u73ED\u53F7"       //航班号,航班数据,行号
						"\u884C\u53F7", "\u822A\u7A7A\u516C\u53F8", "\u822A\u73ED\u53F7","\u7ECF\u505C\u7AD9","\u7EC8\u5230\u7AD9","\u529E\u7968\u65F6\u95F4","\u8D77\u98DE\u65F6\u95F4","\u767B\u673A\u53E3"
				}//界面依次显示:行号、航空公司代号、航班号、经停站、终到站、办票时间、起飞时间和登机口。
		);
		table.setModel(tm/*new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u767B\u673A\u53E3", "\u8D77\u98DE\u65F6\u95F4", "\u529E\u7968\u65F6\u95F4", "\u7EC8\u5230\u7AD9", "\u7ECF\u505C\u7AD9", "\u822A\u7A7A\u516C\u53F8", "\u822A\u73ED\u53F7"
			}
		)*/);
		
		/*table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u822A\u73ED\u53F7", "\u822A\u73ED\u6570\u636E", "\u884C\u53F7"
			}
		));*/
		
		scrollPane.setViewportView(table);
		
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.SOUTH);
		
		btnNewButton = new JButton("Start");//新建start按键并设置功能
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(rece==null)
					rece=new ReceiveAndProcesData();
				rece.execute();
				}
		});
		panel.add(btnNewButton);
		
		btnNewButton_1 = new JButton("Stop");//新建stop按键并设置功能
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) { 
				System.exit(0);                                               //退出系统
			}
		});
		panel.add(btnNewButton_1);
	}

	class ReceiveAndProcesData extends SwingWorker //确定按键
	{

		@Override
		protected void process(List arg0) {
			for(String line:arg0)
			{
				//String test = line.substring(line.indexOf("mvin")+5,line.indexOf("mvin")+9); 
				
				//tm.addRow(new String[]{"待分析",line, " "+count++,"","",""});
				
				//String data=line;
				//List arraylist = new ArrayList();
				//Vector v1=new Vector();
				
				 //if(data.indexOf(key1)>=0)
					 if(line.contains("schd_none"))
	            	{
						 //test="1";//测试
	            		String mvin = line.substring(line.indexOf("mvin")+5,line.indexOf("mvin")+6); 
	            		if(mvin.equals("D"))
	            		{
	            			String flty = line.substring(line.indexOf("flty")+5,line.indexOf("flty")+6);
	            			if(flty.equals("P"))
	            			{
	            				String flin = line.substring(line.indexOf("flin")+5,line.indexOf("flin")+6);
	            				if(flin.equals("D"))
	            				{
	            		
	            			String alcd = line.substring(line.indexOf("alcd")+5,line.indexOf("alcd")+7);
	            			String flno = line.substring(line.indexOf("flno")+5,line.indexOf("flno")+9); 
	            			//System.out.println("flno:"+flno);
	            			if(!list.contains(flno))
	            			{
	            				//System.out.print("11111111111111111");
	            			
	            			list1.add(flno);
	            			
	            			//System.out.print( "航空公司:" + alcd+" 航班号:" +alcd+"-" +flno +" 经停站:");//+" 柜台号:"+ s3+" 柜台开放时间:" + s4
	            			hkgs=alcd;
	            			hbh=flno;
	            			list.add(flno);
	            			num++;
	            		
	            			if(line.contains("rtno=1"))//判断经停站和终到站
	            			{
	            				String rtno1 = line.substring(line.indexOf("rtno=1"),line.indexOf("rtno=1")+42);
	            				if(rtno1.contains("scdt=null")){}
	            				else 
	            				{
	            					String r1=rtno1.substring(rtno1.indexOf("apcd")+5,rtno1.indexOf("apcd")+8);
	            					//System.out.print(r1);
	            					jtz=r1;
	            				}
	            			}
	            			if(line.contains("rtno=2"))
	            			{
	            				String rtno2 = line.substring(line.indexOf("rtno=2"),line.indexOf("rtno=2")+46);
	            				if(rtno2.contains("scdt=null"))
	            				{
	            					
	            					String r2=rtno2.substring(rtno2.indexOf("apcd")+5,rtno2.indexOf("apcd")+8);
	            					//System.out.print("终到站:"+r2+".");
	            					zdz=r2;
	            					
	            				}
	            				else 
	            				{
	            					String r2=rtno2.substring(rtno2.indexOf("apcd")+5,rtno2.indexOf("apcd")+8);
	            					//System.out.print(","+r2);
	            					jtz=jtz+","+r2;
	            				}
	            			}
	            			if(line.contains("rtno=3"))//最多两次经停
	            			{
	            				String rtno3 = line.substring(line.indexOf("rtno=3"),line.indexOf("rtno=3")+46);
	            				String r3=rtno3.substring(rtno3.indexOf("apcd")+5,rtno3.indexOf("apcd")+8);
	            					//System.out.print(" 终到站:"+r3+".");
	            					zdz=r3;
	            			}
	            			String sodt = line.substring(line.indexOf("sodt")+10,line.indexOf("sodt")+14);
	            			//System.out.print(" 办票时间: " );//+sodt +"  "				            
	            			SimpleDateFormat df = new SimpleDateFormat("HHmm");//,Locale.SIMPLIFIED_CHINESE
	            			Date t=null;				            			
	            			try
	            			{
	            				//y=df.parse(sodt);
	            				t=df.parse(sodt);
	            				Date bp1=new Date(t.getTime()-30*60*1000);//起飞前半个小时停止办票
	            				Date bp2=new Date(t.getTime()-90*60*1000);//起飞前一个半小时开始办票
	            				//System.out.print(df.format(bp2)+"-");
	            				//System.out.print(df.format(bp1));
	            				bpsj=df.format(bp2)+df.format(bp1);
	            				//System.out.print(" 起飞时间Dep:"+df.format(t)+" ");//预计起飞时间
	            				bpsj=bpsj.substring(0, 2)+"时"+bpsj.substring(2, 4)+"分-"+bpsj.substring(4, 6)+"时"+bpsj.substring(6,8 )+"分";
	            				qfsj=df.format(t);
	            				qfsj=qfsj.substring(0, 2)+"时"+qfsj.substring(2, 4)+"分";
	            			}
	            			catch(ParseException e)
	            			{
	            				System.out.print("unparseable using"+ df);
	            			}				            							            						            			
	            			tm.addRow(new String[]{ " "+count++,hkgs,hbh,jtz,zdz,bpsj,qfsj,test});
	            				}
	            			}
	            		}
	            		
	            		}
	            	}
					 if(line.contains(key2))
					 {
						// test="3";//测试
							 //System.out.println("222222");
						 String b1 = line.substring(line.indexOf("ffid")+0,line.indexOf("ffid")+19);				        			
		        			list1.add(b1);				        							        							        			
		        			String b2=  line.substring(line.indexOf("chkc")+5,line.indexOf("chkc")+8);
		        			list2.add(b2);
		        			//System.out.println("333333");
		        			//f_bdop=alcd+"-"+flno;
		        			String flno = line.substring(line.indexOf("ffid")+8,line.indexOf("JUN")-5);
		        			//System.out.println(flno);//测试输出
		        			
	            			if(list1.contains(flno))
	                    	   {
	            				System.out.print("等待更新……");
	            			    //int p=list1.indexOf(flno);
	            				//System.out.print("登机口Gate:"+list2.get(p)+" 请前往"+z+"的旅客在此柜台等候");
	            				//djk=list2.get(list22);
	            				//list22++;
	            				djk=b2;
	            				System.out.println("等待更新2……");
	            				if(list.contains(flno))
	            				{
	            					int q=list.indexOf(flno);
	            					//tm.setValueAt("测试成功", q, 7);
	            					tm.setValueAt(djk, q, 7);
	            					    //tm.fireTableChanged(e);
	            					     //tm.fireTableCellUpdated(q, 7);
	            					System.out.println("更新");
	            				}
	            				//publish(list2.get(p));
	            				//arraylist.add(list2.get(p));
	            				//v1.add("登机口Gate:"+list2.get(p)+" 请前往"+z+"的旅客在此柜台等候");
	                    	   }
					 }
					 //--------------------tm.addRow(new String[]{"待分析",line, " "+count++,"登机口:",djk,"test",test,""});
				//Vector v1 = null;
					 //tm.fireTableCellUpdated(row, column);;
					 //tm.setValueAt("测试成功", num, 7);
				//tm.addRow(v1);
			}//for
		}

		@Override
		protected String doInBackground() throws Exception 
		{
			// TODO 自动生成的方法存根
			String line=null;
			try {
				//ByteBuffer buffer = ByteBuffer.allocate(1024);
	            InetAddress remoteIP = InetAddress.getByName(remoteHost);
	            String msg = "Hello Server!";
	            DatagramPacket outputPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, remoteIP, remotePort);
	            socket.send(outputPacket);
	            DatagramPacket inputPacket = new DatagramPacket(new byte[1024], 1024);
	            socket.receive(inputPacket);
	            line = new String(inputPacket.getData(),0 , inputPacket.getLength());;
	            System.out.println("服务器发来的消息,"+line);
				JOptionPane.showMessageDialog(null,"连接服务器成功\r\n\r\n注意:由于数据过多,"
						+ "经测试\r\n在20秒左右开始显示数据\r\n在1分38秒左右会读取到登机口信息\r\n请耐心等待\r\n\r\n"+line);     //弹框,输出连接服务器成功,和line信息
	            while(true) {
	                socket.receive(inputPacket);
	                //buffer.limit(buffer.capacity());
	                //buffer.put(inputPacket.getData());
	                //buffer.flip();
	                //String data  = decode(buffer);
	                //String line = data.substring(0,data.indexOf("\n" + 1));
	                String line1 = new String(inputPacket.getData(),0 , inputPacket.getLength());
	                //System.out.print(line1);
	                publish(line1);
	                //System.out.print(line);
	                if(line1.contains("no data")) {
	                	socket.close();
	                	System.out.println("no data!");
	                	System.out.println("no data!");
	                	System.out.println("no data!");
	                	JOptionPane.showMessageDialog(null,"There is no data!\r\n We will colse the conection"); 
	                    break;
	                }
	            }
	            } catch(Exception e) {
		            e.printStackTrace();
		        }finally {
		            socket.close();
		        }
			return null;
		};
	}
	
}//350

测试文档:fds_data(lab4).txt >>

https://download.csdn.net/download/as1072966956/11904570

若涉及侵权或隐私问题,请联系作者。
 

 

 

 

你可能感兴趣的:(java源码)