java为什么可以部署到不同的服务器上正常运行?

java为什么可以部署到不同的服务器上正常运行?,第1张

楼主要搞清楚一些概念:

1 Java的跨平台是指java应用程序可以运行在windows、linux等操作系统上,而这种跨平台性是通过JVM(java虚拟机)来实现的。

2 而Java EE应用可以部署到tomcat,Weblogic等Web服务器上运行是因为那些Web服务器实现了Java EE规范(servlet、jsp规范等)。

服务器端可以采用多线程处理客户请求,例如:

package threadPool;

import javaioBufferedReader;

import javaioIOException;

import javaioInputStream;

import javaioInputStreamReader;

import javaioOutputStream;

import javaioPrintWriter;

import javanetServerSocket;

import javanetSocket;

import javautilconcurrentExecutorService;

import javautilconcurrentExecutors;

public class ThreadPoolServer {

private int port = 8000;

private ServerSocket serverSocket;

private ExecutorService executorService; //线程池

private final int POOL_SIZE = 4; //单个CPU时线程池中的工作线程数目

public ThreadPoolServer() throws IOException{

serverSocket = new ServerSocket(port);

//创建线程池

//Runtime 的availableProcessors()方法返回当前系统CPU的数目

//系统CPU越多,线程池中的工作线程数目越多

executorService = ExecutorsnewFixedThreadPool(RuntimegetRuntime()availableProcessors()POOL_SIZE);

Systemoutprintln("服务器已启动!!");

}

public void service(){

while(true){

Socket socket = null;

try{

socket = serverSocketaccept();

executorServiceexecute(new Handler(socket));

}catch(IOException e){

eprintStackTrace();

}

}

}

public static void main(String[] args) {

try {

new ThreadPoolServer()service();

} catch (IOException e) {

eprintStackTrace();

}

}

}

class Handler implements Runnable {

private Socket socket;

public Handler(Socket socket) {

thissocket = socket;

}

private PrintWriter getWriter(Socket socket) throws IOException {

OutputStream socketOut = socketgetOutputStream();

return new PrintWriter(socketOut, true);

}

private BufferedReader getReader(Socket socket) throws IOException {

InputStream socketIn = socketgetInputStream();

return new BufferedReader(new InputStreamReader(socketIn));

}

public String echo(String msg) {

return "echo:" + msg;

}

@Override

public void run() {

try {

Systemoutprintln("New connection accepted:" + socketgetInetAddress() + ":" + socketgetPort());

BufferedReader br = getReader(socket);

PrintWriter pw = getWriter(socket);

String msg = null;

while ((msg = brreadLine()) != null) {

Systemoutprintln(msg);

pwprintln(echo(msg));

if (msgequals("bye")) {

break;

}

}

} catch (IOException e) {

eprintStackTrace();

} finally {

try {

if (socket != null)

socketclose();

} catch (IOException e) {

eprintStackTrace();

}

}

}

}

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » java为什么可以部署到不同的服务器上正常运行?

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情