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

📄 ch7.txt

📁 精通Java网络编程代码全部
💻 TXT
字号:
/* 代码7-1
 * Created on 2005-5-14
 */
import java.net.*;
import java.io.*;
public class LocalPortScanner {
	public static void main(String[] args) {
		for (int port = 1; port <= 65535; port++) {
			try {
				// 一旦抛出异常
				//则表示此端口以被别的服务占用
				ServerSocket server = new ServerSocket(port);
			}
			catch (IOException e) {
try {
	//开启一个服务器端口,并进行等待
	ServerSocket httpd = new ServerSocket(5776, 100);
}
catch (IOException e) {
	System.err.println(e);
}


/* 代码7-2
 * Created on 2005-5-14
 */
import java.net.*; 
import java.io.*; 

public class DaytimeServer 
{ 
	public static final int SERVICE_PORT = 13; 
	public static void main(String args[]) 
	{ 
		try 
		{ 
			// 绑定到服务端口,给客户端授予访问TCP daytime服务的权限 
			ServerSocket server = new ServerSocket(SERVICE_PORT); 
			System.out.println ("Daytime service started"); 
			// 无限循环,接受客户端 
			for (;;) 
			{
				// 获取下一个TCP客户端 
				Socket nextClient = server.accept(); 
				// 显示连接细节 
				System.out.println ("Received request from " + 
					nextClient.getInetAddress() + ":" + 
					nextClient.getPort() ); 
				// 不读取数据,只是向消息写信息 
				OutputStream out = 
					nextClient.getOutputStream(); 
				PrintStream pout = new PrintStream (out); 
				// 把当前数据显示给用户 
				pout.print( new java.util.Date() ); 
				// 清除未发送的字节 
				out.flush(); 
				// 关闭流 
				out.close(); 
				// 关闭连接 
				nextClient.close(); 
			} 
		} 
		catch (BindException be) 
		{ 
			//打印错误信息
			System.err.println ("Service already running on port " + SERVICE_PORT ); 
		} 
		catch (IOException ioe) 
		{ 
			System.err.println ("I/O error - " + ioe); 
		} 
	} 
} 



/* 代码7-3
 * Created on 2005-5-14
 */

//通话服务器端
import java.net.*; 
import java.io.*; 
import java.lang.*; 
public class myserver{ 
	public static void main(String args[]){
		//服务器套节字
		ServerSocket server; 
		//客户端套接字
		Socket socket; 
		String s; 
		InputStream Is;//输入流
		OutputStream Os;//输出流
		DataInputStream DIS; 
		PrintStream PS; 
		try{ 
			//在端口4321注册服务 
			server=new ServerSocket(4321); 
			socket=server.accept();//监听窗口,等待连接 
			System.out.println("server ok"); 
			System.out.println("***************** "); 
			System.out.println(""); 
			//获得对应Socket的输入/输出流 
			Is=socket.getInputStream(); 
			Os=socket.getOutputStream(); 
			//建立数据流 
			DIS=new DataInputStream(Is); 
			PS=new PrintStream(Os);
			//建立输入流
			DataInputStream in=new DataInputStream(System.in); 
			while(true){ 
				System.out.println("");
				//打印显示信息
				System.out.println("please wait client's message..."); 
				System.out.println(""); 
				s=DIS.readLine(); //读入从client传来的字符串 
				System.out.println("client said:"+s); //打印字符串 
				if(s.trim().equals("BYE"))break; //如果是"BYE",就退出 
				System.out.print("you say:"); 
				s=in.readLine(); //读取用户输入的字符串 
				PS.println(s); //将读取得字符串传给client 
				if(s.trim().equals("BYE"))break; //如果是"BYE",就退出 
			} 
			//关闭连接 
			DIS.close(); //关闭数据输入流 
			PS.close(); //关闭数据输出流 
			Is.close(); //关闭输入流 
			Os.close(); //关闭输出流 
			socket.close(); //关闭sockey 
		} 
		catch(Exception e){ 
			System.out.println("Error:"+e); 
		} 
	} 
} 
//通话器客户端 
import java.net.*; 
import java.io.*; 
import java.lang.*; 
public class myclient{ 
	public static void main(String args[]){ 
		if (args.length<1){ //判断命令加参数没有 
			System.out.println("you forget the name of the server!"); 
			System.out.println("see also: myclient yxf"); 
			System.exit(1); //如果没加参数就退出 
		} 
		Socket socket; 
		String s="yxfsoft@263.net"; 
		String len; 
		InputStream Is; 
		OutputStream Os; 
		DataInputStream DIS; 
		PrintStream PS; 
		try{ 
			//向主机名为args[0]的服务器申请连接 
			//注意端口号要与服务器保持一致:4321 
			socket=new Socket(args[0],4321); 
			System.out.println("client ok"); 
			System.out.println("******************** "); 
			System.out.println(""); 
			//获得对应socket的输入/输出流 
			Is=socket.getInputStream(); 
			Os=socket.getOutputStream(); 
			//建立数据流 
			DIS=new DataInputStream(Is); 
			PS=new PrintStream(Os); 
			DataInputStream in=new DataInputStream(System.in); 
			while(true){
				System.out.print("you say:"); 
				s=in.readLine(); //读取用户输入的字符串 
				PS.println(s); //将读取得字符串传给server 
				if(s.trim().equals("BYE"))break; //如果是"BYE",就退出 
				else 
				{ 
					System.out.println(""); 
					System.out.println("please wait server's message..."); 
					System.out.println(""); 
				} 
				s=DIS.readLine(); //从服务器获得字符串 
				System.out.println("server said:"+s); //打印字符串 
				if(s.trim().equals("BYE"))break; //如果是"BYE",就退出 
			} 
			//关闭连接 
			DIS.close(); //关闭数据输入流 
			PS.close(); //关闭数据输出流 
			Is.close(); //关闭输入流 
			Os.close(); //关闭输出流 
			socket.close(); //关闭socket 
		} 
		catch(Exception e){ 
			System.out.println("Error:"+e); 
		} 
	} 
}


/* 代码7-4
 * Created on 2005-5-14
 */
import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;
public class httpServer{
	public static void main(String args[]) {
		port;
		ServerSocket server_socket;
		//读取服务器端口号
		try {
			//获得端口号
			port = Integer.parseInt(args[0]);
		}
		catch (Exception e) {
			port = 8080;//设定端口号
		}
		try {
			//监听服务器端口,等待连接请求
			server_socket = new ServerSocket(port);
			System.out.println("httpServer running on port "
				+server_socket.getLocalPort());//当前HTTP服务器设立的端口号
		}




/* 代码7-5
 * Created on 2005-5-14
 */
class httpRequestHandler implements Runnable
{
	final static String CRLF = "\r\n";
	//设置端口
	Socket socket;
//设置输入流
	InputStream input;
//设置输出流
	OutputStream output;
//通过缓存的方式
	BufferedReader br;
	// 构造方法
	public httpRequestHandler(Socket socket) throws Exception
	{
		this.socket = socket;
		//得到输入输出流
		this.input = socket.getInputStream();//获得输入流
		this.output = socket.getOutputStream();//获得输出流
		this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));//通过装饰类封装输入流
	}
	
	// 实现Runnable 接口的run()方法
	public void run()
	{
		try {
			processRequest();
		}
		catch(Exception e) {
			System.out.println(e);//输出错误信息
		}
	}




/* 代码7-6
 * Created on 2005-5-14
 */
private void processRequest() throws Exception
{
while(true) {
//读取并显示Web 浏览器提交的请求信息
String headerLine = br.readLine();
System.out.println("The client request is "+ headerLine);
if(headerLine.equals(CRLF) || headerLine.equals("")) break;
//根据请求字符串中的空格拆分客户请求
StringTokenizer s = new StringTokenizer(headerLine);
String temp = s.nextToken();//按段获取信息
if(temp.equals("GET")) {
String fileName = s.nextToken();
fileName = "." + fileName ;
}

/* 代码7-7
 * Created on 2005-5-14
 */
//HttpProxy.java
/*************************************
* 一个基础的代理服务器类
*************************************
*/
import java.net.*;
import java.io.*;

public class HttpProxy extends Thread {
static public int CONNECT_RETRIES=5;//设置重连次数
static public int CONNECT_PAUSE=5;//设置停止时间
static public int TIMEOUT=50;
static public int BUFSIZ=1024;//设置缓冲区大小
static public boolean logging = false;
static public OutputStream log=null;//记录日志信息
// 传入数据用的Socket
protected Socket socket;
// 上级代理服务器,可选
static private String parent=null;
static private int parentPort=-1;
//设定上级代理服务器
static public void setParentProxy(String name, int pport) {
parent=name;
parentPort=pport;
}
	
// 在给定Socket上创建一个代理线程。
public HttpProxy(Socket s) { socket=s; start(); }
//在日志文件中记录
public void writeLog(int c, boolean browser) throws IOException {
log.write(c);
}
//通过字符串的方式在日志文件中记录
public void writeLog(byte[] bytes,int offset,
		int len, boolean browser) throws IOException {
for (int i=0;i<len;i++) writeLog((int)bytes[offset+i],browser);
}
	
// 默认情况下,日志信息输出到
// 标准输出设备,
// 派生类可以覆盖它
public String processHostName(String url, String host, int port, Socket sock) {
java.text.DateFormat cal=java.text.DateFormat.getDateTimeInstance();
System.out.println(cal.format(new java.util.Date()) + " - " +
			url + " " + sock.getInetAddress()+"<BR>");
return host;
}




/* 代码7-8
 * Created on 2005-5-14
 */
// 执行操作的线程
public void run() {
    String line;
    String host;
    int port=80;//设置端口号
	Socket outbound=null;
    try {
        socket.setSoTimeout(TIMEOUT);//设置停止时间
        InputStream is=socket.getInputStream();//通过套接字,获得输入流
        OutputStream os=null;//输出流
        try {
			// 获取请求行的内容
			line="";
			host="";
			int state=0;//状态信息
			boolean space;
			while (true) {
				int c=is.read();//以整数形式读入
				if (c==-1) break;//跳出循环
				if (logging) writeLog(c,true);
				space=Character.isWhitespace((char)c); 
				//通过状态的转换
				switch (state) {
				case 0:
					if (space) continue; 
					state=1;
				case 1:
					if (space) {
						state=2;
						continue;
					}
					line=line+(char)c;
					break;
				case 2:
					if (space) continue; // 跳过多个空白字符
					state=3;
				case 3:
					if (space) {
						state=4;
						// 只分析主机名称部分
						String host0=host;
						int n;
						n=host.indexOf("//");
						if (n!=-1) host=host.substring(n+2);
						n=host.indexOf('/');
						if (n!=-1) host=host.substring(0,n);
						// 分析可能存在的端口号
						n=host.indexOf(":");
						if (n!=-1) { 
							port=Integer.parseInt(host.substring(n+1));//得到端口信息
							host=host.substring(0,n);
						}
						host=processHostName(host0,host,port,socket);
						if (parent!=null) {
							host=parent;
							port=parentPort;
						}
						int retry=CONNECT_RETRIES;
						while (retry--!=0) {
							try {
								outbound=new Socket(host,port);//得到输出套接字
								break;
                } catch (Exception e) { }
                // 等待
                Thread.sleep(CONNECT_PAUSE);
						}
						if (outbound==null) break;
						outbound.setSoTimeout(TIMEOUT);
						os=outbound.getOutputStream();
						os.write(line.getBytes());//将内容以写缓冲的方式写入
						os.write(' ');
						os.write(host0.getBytes());
						os.write(' ');//写入空字符串
						pipe(is,outbound.getInputStream(),os,socket.getOutputStream());
						break;//跳出循环
					}
					host=host+(char)c;
					break;
				}
			}
        }
        catch (IOException e) { }
		
    } catch (Exception e) { }
    finally {
		try { socket.close();} catch (Exception e1) {}
		try { outbound.close();} catch (Exception e2) {}
	}
}




/* 代码7-9
 * Created on 2005-5-14
 */

// 测试用的简单main方法
static public void main(String args[]) {
    System.out.println("在端口808启动代理服务器\n");//启动代理服务器
    HttpProxy.log=System.out;
    HttpProxy.logging=false;
    HttpProxy.startProxy(808,HttpProxy.class);//在端口808上启动服务器
}
}




/* 代码7-10
 * Created on 2005-5-14
 */
static public void startProxy(int port,Class clobj) {
	ServerSocket ssock;//设置服务器套接字
	Socket sock;
	try {
		ssock=new ServerSocket(port);
		while (true) {
			Class [] sarg = new Class[1];
			Object [] arg= new Object[1];
			sarg[0]=Socket.class;
			try {
				java.lang.reflect.Constructor cons = clobj.getDeclaredConstructor(sarg);
				arg[0]=ssock.accept();//接收新的客户端连接
				cons.newInstance(arg); // 创建HttpProxy或其派生类的实例
			} catch (Exception e) { 
				Socket esock = (Socket)arg[0];
				try { esock.close(); } catch (Exception ec) {}
			}
		}
	} catch (IOException e) {
	}
}






⌨️ 快捷键说明

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