手机版

宁波工程学院 2011-2012 学年第 2 学期_Java程序设计(4)

时间:2025-07-15   来源:未知    
字号:

服务器端程序: ; import java.io.*; import java.util.Date;

class { private Socket connection;

public JTimeThread(Socket connection) { this.connection = connection; } public void run() { try {

Date now = new Date();

long netTime = now.getTime()/1000 + 2208988800L;

byte[] time = new byte[4]; for(int i=0; i<4; i++) {

; netTime >>= 8; }

//获取套接字输入流,并写入网络时间 OutputStream out = connection.getOutputStream(); out.write(time); out.flush(); }

catch(IOException e) { } finally { try {

if (connection != null) connection.close(); } catch (IOException e) {} } } }

public class JTimeServer2 { private int port; public JTimeServer2() {

this(37);//时间服务器默认端口号37 }

public JTimeServer2(int port) { this.port = port; }

public void run() {

ServerSocket server = null; try {

server = new ServerSocket(port); while(true) { try {

//等待客户端连接请求

Socket connection = server.accept(); //创建并启动一个JTimeThread线程来服务客户端请求

(new JTimeThread(connection)).start(); }

catch (IOException e) { } } }

catch(IOException e) { }

finally { //关闭服务器Socket try {

if(null != server) } catch (IOException e) {} } }

public static void main(String[] args) { JTimeServer2 timeServer = null; if(args.length == 0) { timeServer = new JTimeServer2(); } else if(args.length == 1) {//命令行参数指定时间服务器监听端口 timeServer = new JTimeServer2(Integer.parseInt(args[0])); } else { System.out.println("Usage: java JTimeServer2 Port"); return; } //启动始终服务器 (new Thread(timeServer)).start(); } }

问题1:填上程序空缺部分,使之成为完整的程序:

① JTimeClient ; ② (netTime << 8) | in.read() ; ② IOException ; ④ socket.close() ; ⑤ import .* ; ⑥ JTimeThread extends Thread ; ⑦ time[3-i]=(byte)(netTime&0x0FFL) ; ⑧ implements Runable ; ⑨ server.close(); 。

问题2:该服务器程序能否为多个客户端服务。 V可以 不可以

宁波工程学院 2011-2012 学年第 2 学期_Java程序设计(4).doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
×
二维码
× 游客快捷下载通道(下载后可以自由复制和排版)
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
注:下载文档有可能出现无法下载或内容有问题,请联系客服协助您处理。
× 常见问题(客服时间:周一到周五 9:30-18:00)