⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mpserver.java

📁 Java开发的实现TCP/IP协议的服务器端程序。极具扩展性。可供初学者使用。希望对他们有用。
💻 JAVA
字号:
/*
 * Copyright (c) 2008 By Zibo Magnifico.  All rights reserved.
 * This code is one resource of Zibo Magnifico Electronic Commerce Recrut Co. Ltd.,
 * Author: Fengwen Pan
 * Date  : 2008.12.10
 */
package com.MPServer;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * This class is a flexible, multi-threaded server.
 **/
public class MPServer {
	static int MAXCONNECTIONS = 10;  	// 并发数目,可写在配置文件中
	static int SERVERPORT     = 2345;   // 设置本服务器监听端口,可写在配置文件中.

	int iConnection = 0;    // 当前打开的线程数目
	PrintWriter logStream;  // Where we write our logging output to

	public static void main(String[] args) {
		try {
			ServerSocket srvSocket; // The socket to listen for connections from client

			MPServer s = new MPServer(System.out, MAXCONNECTIONS);
			
			srvSocket  = new ServerSocket(SERVERPORT);
			//srvSocket.setSoTimeout(600000);  // access timeout(慎用)

			System.out.println("服务器准备就绪,端口号:"+ SERVERPORT);
			//s.log( "Starting service on port " + SERVERPORT );
			while (true) {
				doService newUser = new doService(srvSocket.accept(), s);
				newUser.start();
			}
		} catch (Exception e) {
			System.err.println("Server: " + e);
			System.exit(1);
		}
	}

	/**
	 * This is the MPServer() constructor.  It must be passed a stream 
	 * to send log output to (may be null).  
	 **/
	public MPServer(OutputStream logStream, int maxConnections) {
		setLogStream(logStream);
		iConnection = 0;
	}

	/** 
	 * 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());
	}

	// 连接数+-1 或者返回当前连接数
	// if iFlag==-1, then -
	// if iFlag==+1, then +
	// else if iFlag==0 then return 当前连接数
	// !! iFlag = {-1,0,1};
	protected synchronized int opConnNum(int iFlag) {
		return iConnection += iFlag;
		
		/*(if( iFlag == 1 ){
			iConnection += 1;
			return 1;
		}else if( iFlag == -1 ){
			iConnection -= 1;
			return 1;
		}else{
			return iConnection;
		}*/
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -