[英]NTP for TCP/IP(server-client)
i have a simple server... 我有一个简单的服务器...
public static void main(String[] args) throws Exception{
ServerSocket server = new ServerSocket(2000);
Socket sock = server.accept();
InputStream in = sock.getInputStream();
OutputStream out = sock.getOutputStream();
PrintWriter w = new PrintWriter(out);
Scanner s = new Scanner(in);
...
and a simple client... 和一个简单的客户...
public static void main(String[] args) throws Exception{
Socket sock = new Socket("localhost",2000);;
InputStream in= sock.getInputStream();
OutputStream out = sock.getOutputStream();
PrintWriter w = new PrintWriter(out);
Scanner s = new Scanner(in);
....
-how can i connect more clients to this server? -如何将更多客户端连接到该服务器? (I need 2 more) -also i want to send system time from server to clients and then clients will send back their time 10 times each plus some fixed delay (0.5-1 sec) then the server must find the average from all delays and send it back to the clients as the new time...
(我还需要2个)-我也想从服务器向客户端发送系统时间,然后客户端将向其发送10次时间,每个时间再加上固定的延迟时间(0.5-1秒),然后服务器必须从所有延迟中找到平均值,并且将其作为新时间发送给客户...
thank you for your time... 感谢您的时间...
System.currentTimeMillis()
provides the system time System.currentTimeMillis()
提供系统时间
Every Socket returned by server.accept()
is a separate object and your server can communicate independently with each client through each Socket object. server.accept()
返回的每个Socket都是一个单独的对象,您的服务器可以通过每个Socket对象与每个客户端独立通信。 However, since your application is time-sensitive, I would recommend using a separate thread for each client. 但是,由于您的应用程序对时间敏感,因此我建议为每个客户端使用单独的线程。
A simple server would be: 一个简单的服务器将是:
ServerSocket serverSock = new ServerSocket(2000);
while (true)
{
Socket fpSock = serverSock.accept();
MyThread t = new MyThread(fpSock, this);
t.start();
}
The processing you need will be done in the MyThread run() method. 您需要的处理将在MyThread run()方法中完成。 "this" is passed to the thread to provide a reference where each thread can callback to methods in the main class.
“ this”被传递给线程以提供一个引用,每个线程可以在其中回调到主类中的方法。 Make sure to make such methods
synchronized
. 确保使这些方法
synchronized
。
You also don't necessarily need to send the server's time to the client, simply send a generic packet which the client is expected to echo back. 您也不一定需要将服务器的时间发送给客户端,只需发送一个普通的数据包即可,希望客户端回显该数据包。 Use the server's timestamp for all transactions to avoid variation in client system time.
将服务器的时间戳记用于所有事务,以避免客户端系统时间发生变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.