/*
* Copyright (c) 2000 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.com/javaexamples2.
*/
package com.davidflanagan.examples.net;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* This class is a generic framework for a flexible, multi-threaded server.
* It listens on any number of specified ports, and, when it receives a
* connection on a port, passes input and output streams to a specified Service
* object which provides the actual service. It can limit the number of
* concurrent connections, and logs activity to a specified stream.
**/
public class Server {
/**
* A main() method for running the server as a standalone program. The
* command-line arguments to the program should be pairs of servicenames
* and port numbers. For each pair, the program will dynamically load the
* named Service class, instantiate it, and tell the server to provide
* that Service on the specified port. The special -control argument
* should be followed by a password and port, and will start special
* server control service running on the specified port, protected by the
* specified password.
**/
public static void main(String[] args) {
try {
if (args.length < 2) // Check number of arguments
throw new IllegalArgumentException("Must specify a service");
// Create a Server object that uses standard out as its log and
// has a limit of ten concurrent connections at once.
Server s = new Server(System.out, 10);
// Parse the argument list
int i = 0;
while(i < args.length) {
if (args[i].equals("-control")) { // Handle the -control arg
i++;
String password = args[i++];
int port = Integer.parseInt(args[i++]);
// add control service
s.addService(new Control(s, password), port);
}
else {
// Otherwise start a named service on the specified port.
// Dynamically load and instantiate a Service class
String serviceName = args[i++];
Class serviceClass = Class.forName(serviceName);
Service service = (Service)serviceClass.newInstance();
int port = Integer.parseInt(args[i++]);
s.addService(service, port);
}
}
}
catch (Exception e) { // Display a message if anything goes wrong
System.err.println("Server: " + e);
System.err.println("Usage: java Server " +
"[-control <password> <port>] " +
"[<servicename> <port> ... ]");
System.exit(1);
}
}
// This is the state for the server
Map services; // Hashtable mapping ports to Listeners
Set connections; // The set of current connections
int maxConnections; // The concurrent connection limit
ThreadGroup threadGroup; // The threadgroup for all our threads
PrintWriter logStream; // Where we send our logging output to
/**
* This is the Server() constructor. It must be passed a stream
* to send log output to (may be null), and the limit on the number of
* concurrent connections.
**/
public Server(OutputStream logStream, int maxConnections) {
setLogStream(logStream);
log("Starting server");
threadGroup = new ThreadGroup(Server.class.getName());
this.maxConnections = maxConnections;
services = new HashMap();
connections = new HashSet(maxConnections);
}
/**
* A public method to set the current logging stream. Pass null
* to turn logging off
**/
public synchronized void setLogStream(OutputStream out) {
if (out != null) logStream = new PrintWriter(out);
else logStream = null;
}
/** Write the specified string to the log */
protected synchronized void log(String s) {
if (logStream != null) {
logStream.println("[" + new Date() + "] " + s);
logStream.flush();
}
}
/** Write the specified object to the log */
protected void log(Object o) { log(o.toString()); }
/**
* This method makes the server start providing a new service.
* It runs the specified Service object on the specified port.
**/
public synchronized void addService(Service service, int port)
throws IOException
{
Integer key = new Integer(port); // the hashtable key
// Check whether a service is already on that port
if (services.get(key) != null)
throw new IllegalArgumentException("Port " + port +
" already in use.");
// Create a Listener object to listen for connections on the port
Listener listener = new Listener(threadGroup, port, service);
// Store it in the hashtable
services.put(key, listener);
// Log it
log("Starting service " + service.getClass().getName() +
" on port " + port);
// Start the listener running.
listener.start();
}
/**
* This method makes the server stop providing a service on a port.
* It does not terminate any pending connections to that service, merely
* causes the server to stop accepting new connections
**/
public synchronized void removeService(int port) {
Integer key = new Integer(port); // hashtable key
// Look up the Listener object for the port in the hashtable
final Listener listener = (Listener) services.get(key);
if (listener == null) return;
// Ask the listener to stop
listener.pleaseStop();
// Remove it from the hashtable
services.remove(key);
// And log it.
log("Stopping service " + listener.service.getClass().getName() +
" on port " + port);
}
/**
* This nested Thread subclass is a "listener". It listens for
* connections on a specified port (using a ServerSocket) and when it gets
* a connection request, it calls the servers addConnection() method to
* accept (or reject) the connection. There is one Listener for each
* Service being provided by the Server.
**/
public class Listener extends Thread {
ServerSocket listen_socket; // The socket to listen for connections
int port; // The port we're listening on
Service service; // The service to provide on that port
volatile boolean stop = false; // Whether we've been asked to stop
/**
* The Listener constructor creates a thread for itself in the
* threadgroup. It creates a ServerSocket to listen for connections
* on the specified port. It arranges for the ServerSocket to be
* interruptible, so that services can be removed from the server.
**/
public Listener(ThreadGroup group, int port, Service service)
throws IOException
{
super(group, "Listener:" + port);
listen_socket = new ServerSocket(port);
// give it a non-zero timeout so accept() can be interrupted
listen_socket.setSoTimeout(600000);
this.port = port;
this.service = service;
}
/**
* This is the polite way to get a Listener to stop accepting
* connections
***/
public void pleaseStop() {
this.st
没有合适的资源?快使用搜索试试~ 我知道了~
164个完整的Java代码.rar_java代码_个
共207个文件
java:163个
html:14个
gif:6个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 38 浏览量
2022-09-24
12:17:19
上传
评论
收藏 416KB RAR 举报
温馨提示
"164个完整的Java代码.rar"是一个压缩包,其中包含了164个Java编程语言的示例代码。这些代码实例旨在提供全面的Java编程知识,帮助学习者理解并掌握Java语言的核心概念和技术。 指出,这个资源是"非常典型的"和"很好的",意味着它包含了一系列具有代表性的Java代码片段,覆盖了多种编程场景和问题解决策略。这些代码可能涉及基础语法、数据结构、控制流程、面向对象编程、异常处理、多线程、网络编程、I/O流、数据库操作、图形用户界面(GUI)开发以及Java集合框架等广泛主题。通过这些代码,学习者可以深入学习和实践,提升自己的Java编程技能。 "java代码"和"个"进一步强调了这是关于Java编程的代码集合,且数量为164个独立的代码实例。 【压缩包子文件的文件名称列表】中,"www.pudn.com.txt"可能是提供这些代码来源的网站信息或下载链接的文本文件,而"164个完整的Java代码"很可能是一个包含所有代码实例的文件,例如一个包含多个类的Java源代码文件夹或者一个PDF文档,详细列出了每一个代码示例及其解释。 从这些信息可以推断,这个压缩包是一个宝贵的教育资源,适合初学者和有一定经验的开发者。对于初学者,它可以作为学习Java语法和编程实践的起点;对于有经验的开发者,它可能是复习基础知识、查找特定问题解决方案或激发新项目灵感的宝贵资料。在实际使用时,学习者应逐个研究代码,理解其工作原理,然后尝试修改和扩展,以加深对Java语言的理解。同时,与社区或其他学习者交流这些代码,分享心得,也是提升编程能力的有效途径。
资源推荐
资源详情
资源评论
收起资源包目录
164个完整的Java代码.rar_java代码_个 (207个子文件)
chirp.au 1KB
classlist 24KB
web-app_2.2.dtd 18KB
java_parts.gif 14KB
cover.gif 6KB
YesNoPanelIcon.gif 4KB
tiger.gif 4KB
cover.gif 4KB
background.gif 76B
index.html 17KB
LICENSE.html 3KB
Soundmap.html 1KB
ColorGradient.html 254B
ColorScribble.html 213B
BouncingCircle.html 161B
GraphicsSampler.html 130B
AppletMenuBarDemo.html 129B
FirstApplet.html 125B
EventTester.html 125B
FontList.html 123B
Scribble.html 122B
Clock.html 118B
Who.html 113B
Server.java 26KB
MudClient.java 21KB
MudPlace.java 18KB
HardcopyWriter.java 16KB
Manifest.java 16KB
WebBrowser.java 16KB
Sorter.java 13KB
PrintableDocument.java 13KB
ScribbleDragAndDrop.java 12KB
RemoteDBBankServer.java 12KB
PrintableDocument.java 12KB
ItemChooser.java 11KB
ExecuteSQL.java 11KB
Scribble.java 10KB
LookupAPI.java 10KB
GUIResourceBundle.java 9KB
ShowComponent.java 9KB
FileLister.java 9KB
MakeAPIDB.java 9KB
Spiral.java 9KB
AppletMenuBar.java 8KB
Command.java 8KB
EventTestPane.java 8KB
FontChooser.java 8KB
Mud.java 8KB
Timer.java 8KB
GraphicsExampleFrame.java 7KB
CustomStrokes.java 7KB
Counter.java 7KB
ComponentTree.java 7KB
ThemeManager.java 7KB
Bank.java 7KB
ScribbleCutAndPaste.java 7KB
UnicodeDisplay.java 7KB
DOMTreeWalkerTreeModel.java 7KB
MudServer.java 6KB
YesNoPanel.java 6KB
TripleDES.java 6KB
RemoteBankServer.java 6KB
MultiLineLabel.java 6KB
WebAppConfig.java 6KB
Paints.java 6KB
ProxyServer.java 6KB
GraphicsSampler.java 6KB
Scribble.java 6KB
FileViewer.java 6KB
CompositeEffects.java 6KB
SimpleProxyServer.java 6KB
Soundmap.java 6KB
PropertyTable.java 6KB
ScribblePrinter2.java 6KB
HTMLWriter.java 6KB
ListServlets2.java 6KB
ShowClass.java 5KB
FileCopy.java 5KB
GetDBInfo.java 5KB
ColumnLayout.java 5KB
ImageOps.java 5KB
Hypnosis.java 5KB
ListServlets1.java 5KB
LinkedList.java 5KB
XMLDocumentWriter.java 5KB
EventTester.java 5KB
DecorBox.java 5KB
Query.java 5KB
GenericClient.java 5KB
GenericPaint.java 5KB
YesNoPanelCustomizer.java 5KB
WebAppConfig2.java 5KB
LocalizedError.java 4KB
Serializer.java 4KB
ScribblePrinter1.java 4KB
Compress.java 4KB
Who.java 4KB
SimpleCutAndPaste.java 4KB
SimpleMenu.java 4KB
RemoveHTMLReader.java 4KB
共 207 条
- 1
- 2
- 3
资源评论
JonSco
- 粉丝: 94
- 资源: 1万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 基于Vue和SpringBoot的企业员工管理系统2.0版本设计源码
- 【C++初级程序设计·配套源码】第2期-基本数据类型
- 基于Java和Vue的kopsoftKANBAN车间电子看板设计源码
- 影驰战将PS3111 东芝芯片TT18G23AIN开卡成功分享,图片里面画线的选项很重要
- 【C++初级程序设计·配套源码】第1期-语法基础
- 基于JavaScript、CSS、HTML的简易DOM版飞机游戏设计源码
- 基于Java开发的日程管理FlexTime应用设计源码
- SM2258XT-BGA144-4BGA180-6L-R1019 三星KLUCG4J1CB B0B1颗粒开盘工具 , EC, 3A, 94, 43, A4, CA 七彩虹SL300这个固件有用
- GJB 5236-2004 军用软件质量度量
- 30天开发操作系统 第 8 天 - 鼠标控制与切换32模式
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功