服务器 - 客户端NTP项目 - NullPointerException / SocketException问题

时间:2013-05-16 23:51:59

标签: java multithreading sockets client-server ntp

我有关于我正在处理的服务器 - 客户端NTP项目的代码...当我运行它时,我得到一个“java.lang.NullPointerException”...

-NullPointerException修复...我初始化套接字但我得到java.net.SocketException:Socket未连接此错误。有线索吗?

有人可以帮助我吗?

package ntp;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @author Anastasis Chirstodoulakis
 */
public class Server extends Thread {
    private int totalTime=0;
    private int x=0;          //counter
    private int moTime=0;     //average time
    private int PORT;
    private Socket sock = new Socket();

    public Server(int PORT) {
        this.PORT=PORT;
    }

    private Server(Socket sock) {
        this.sock = sock;
    }

    @Override
    public void run(){
        try {
            //open socket
            ServerSocket server = new ServerSocket(PORT);
            InputStream  in = sock.getInputStream(); 
            OutputStream out = sock.getOutputStream();
            PrintWriter w = new PrintWriter(out);   //buffer
            Scanner s = new Scanner(in);
            SimpleDateFormat time = new SimpleDateFormat("HH.mm.ss."); 

            while(true){
                sock = server.accept();
                new Thread(new Server(sock)).start();

                String msg=s.nextLine();
                System.out.println(msg);
                //get time and set format
                Date date=new Date();       //get current time
                SimpleDateFormat sd=new SimpleDateFormat("yyyy.MM.dd.HH:mm:ss");    
                String sdf=sd.format(date);
                //convert time into seconds
                String arr[]=msg.split(" ");
                String st=arr[3];
                String arr1[]=st.split("\\.");
                int hh=Integer.parseInt(arr1[0]);
                int mm=Integer.parseInt(arr1[1]);
                int ss=Integer.parseInt(arr1[2]);
                int secTime=(3600*hh)+(60*mm)+ss;

                totalTime += secTime;
                x++; 

                if(x==10){
                    moTime=totalTime/10;    //to get average time

                    String moHour= secToTime(moTime);                
                    w.println("Server time is:"+ moHour);
                    w.flush();  //to empty the buffer
                }
                in.close();
                out.close();
                sock.close();
            }
        }
        catch (IOException ex) {
            System.out.println(ex); 
        }
        catch (NullPointerException ex){
            System.out.println(ex);
        }
    }      

    public String secToTime(int totalSec){
        //seconds to HH,mm,ss
        int hour=totalSec/3600;
        int remain=totalSec%3600;
        int min=remain/60;
        int sec=remain%60;

        String hours = (hour < 10 ? "0" : "") + hour,
        mins = (min < 10 ? "0" : "") + min,
        secs = (sec < 10 ? "0" : "") + sec;
        String send = hours + "." + mins + "." + secs + ".";

        return send;
      }
}

这是客户端代码,但我认为没问题......

package ntp;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @author Anastasis Christodoulakis
 */
public class Client extends Thread{
    private Random r;
    private int PORT;

    public Client(int PORT) {
        this.PORT=PORT;
        r = new Random();
    }

    public String secToTime(int totalSec){
        //seconds to HH,mm,ss
        int hour=totalSec/3600;
        int remain=totalSec%3600;
        int min=remain/60;
        int sec=remain%60;

        String hours = (hour < 10 ? "0" : "") + hour,
        mins = (min < 10 ? "0" : "") + min,
        secs = (sec < 10 ? "0" : "") + sec;
        String send = hours + "." + mins + "." + secs + ".";

        return send;
      }

    @Override
    public void run(){        
        try {
            //open socket
            Socket sock=new Socket("localhost",PORT);          
            InputStream in=sock.getInputStream();
            OutputStream out=sock.getOutputStream();         
            Scanner s=new Scanner(in);
            PrintWriter w=new PrintWriter(out); //buffer

            for(int i=0;i<10;i++){
                Date today=new Date();     //get current time
                SimpleDateFormat sd=new SimpleDateFormat("yyy.MM.dd.HH.mm.ss");  //change time form
                String sdf=sd.format(today); //time to String

                 //convert time into seconds        
                String ms[]=sdf.split("\\.");
                int hh=Integer.parseInt(ms[3]);                
                int mm=Integer.parseInt(ms[4]);            
                int ss=Integer.parseInt(ms[5]);              
                int secTime=(3600*hh)+(60*mm)+ss; 

                //Random Delay (-0.5/0.5)
                float lag=r.nextFloat()*(0.5f-0.5f)+0.5f;
                secTime= (secTime - (int) (2 - lag));

                w.println("Client time is: " + secToTime(secTime));
                w.flush();      

            }
            while(s.hasNextLine()){
                String input=s.nextLine();
                System.out.println(input);
            }

            in.close();
            out.close();
            sock.close();
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }    
}

和主要......

package ntp;

public class NTP {


    public static void main(String[] args) {
        Server server = new Server(2000);   //set port
        Client client = new Client(2000);

        server.start();
        client.start();
    }
}

............... .................... ............ ....... ...............

感谢您的时间。

2 个答案:

答案 0 :(得分:1)

如果这应该是真正的NTP:NTP是数据报协议,而不是字节流协议。尝试使用流实现它是一个非首发。 NTP是无连接的。 Streams需要两个相互连接的端点。

如果这应该是您自己通过TCP实现的协议:您必须先连接流套接字才能使用其流。在服务器端,那是accept。在客户端,那是connect

答案 1 :(得分:0)

在运行服务器之前,首先需要setSock。

package ntp;

public class NTP {


public static void main(String[] args) {
    Server server = new Server(2000);   //set port
    server.setSocket(new Socket()); // you also need write setter for socket.
    Client client = new Client(2000);

    server.start();
    client.start();
   }
}

.......