`
阿尔萨斯
  • 浏览: 4472103 次
社区版块
存档分类
最新评论

JAVA进阶-网络编程

 
阅读更多
>通过套接字连接服务器
Socket指代套接字


>读取任意网站的首页
---------
/**
 * 	@author Lean  @date:2014-10-9  
 */
public class SocketSample {
	
	public static void main(String[] args) {
		BufferedWriter writer=null;
		Socket socket=null;
		try {
			while (true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				socket=new Socket("localhost",8080);
				OutputStream outputStream=socket.getOutputStream();
				outputStream.write("GET / HTTP/1.0\n\n".getBytes());
				BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
				writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:/Users/Administrator/Desktop/TheadSample.html")));
				String appendStr=null;
				while ((appendStr=reader.readLine()) != null) {
//					System.out.println(appendStr);
					writer.write(appendStr);
				}
				writer.close();
				reader.close();
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (socket!=null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		
		
	}
	
}
---------
>通过url下载任意网页
---------
/**
 * 	@author Lean  @date:2014-10-9  
 */
public class URLSample {
	
	public static void main(String[] args) {
		
		try {
			URL url=new URL("HTTP","www.baidu.com",80,"");
//			URL url=new URL("http://www.baidu.com");
			HttpURLConnection connection=(HttpURLConnection) url.openConnection();
			connection.connect();
			InputStream is=connection.getInputStream();
			byte[] buff=new byte[1024];
			int length=0;
			while ((length=is.read(buff))!=-1) {
				System.out.println(new String(buff));
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}
	
}
---------
>检测网站传入的cookie信息
---------
/**
 * 	@author Lean  @date:2014-10-9  
 */
public class HttpCookieSample {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CookieManager manager=new CookieManager();
		manager.setCookiePolicy(new CustomerPolicy());
		CookieHandler.setDefault(manager);
		try {
			URL url=new URL("http://www.baidu.com");
			URLConnection conn=url.openConnection();
			Object content=conn.getContent();
			List<HttpCookie> cookies=manager.getCookieStore().getCookies();
			for (HttpCookie httpCookie : cookies) {
				System.out.println(httpCookie.getName()+"  "+httpCookie.getValue()+"    "+httpCookie.getDomain());
				printCookieLiveAge(httpCookie);
				System.out.println("Cookie secured:"+httpCookie.getSecure());
				System.out.println("...........");
				
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	private static void printCookieLiveAge(HttpCookie httpCookie) {
		long age=httpCookie.getMaxAge();
		SimpleDateFormat df=new SimpleDateFormat("HH:mm:ss");
		System.out.println(age!=-1?"Cookie will expire when close ":"Cookie age is:"+df.format(age));
	}
	
	static class CustomerPolicy implements CookiePolicy{

		@Override
		public boolean shouldAccept(URI uri, HttpCookie cookie) {
			return true;
		}
		
	}
	
}
---------
>编写同时服务多个客户端的服务器程序
---------
/**
 * 	@author Lean  @date:2014-10-9  
 */
public class ServerSocketSample {
	
	private static ServerSocket server=null;
	
	public static void main(String[] args) {
		
		try {
			server=new ServerSocket(8080);
			ExecutorService pool=Executors.newFixedThreadPool(3);
			while (true) {
				Socket socketObject= server.accept();
				pool.submit(new CustomRunnable(socketObject));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	static class CustomRunnable implements Runnable{
		
		byte[] buff=new byte[512];
		private Socket socketObject;
		public CustomRunnable(Socket socketObject) {
			this.socketObject=socketObject;
		}

		@Override
		public void run() {
			try {
				System.out.println("Thread ID>>"+Thread.currentThread().getId());
				InputStream stream=socketObject.getInputStream();
				stream.read(buff);
				OutputStream os=socketObject.getOutputStream();
				os.write(buff);
				socketObject.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
---------
>编写实际的文件存储服务器程序
---------

StorgeServerSample

/**
 * 	@author Lean  @date:2014-10-10  
 */
public class StorgeServerSample {
	
	public static void main(String[] args) {
		ServerSocket socket=null;
		ExecutorService service=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
		try {
			socket=new ServerSocket(8080);
			try {
				while (true) {
					Socket socketObject=socket.accept();
					service.submit(new RequestRunnable(socketObject));
				}
			} finally{
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	static class RequestRunnable implements Runnable{
		
		private Socket requestSocket;

		public RequestRunnable(Socket socketObject) {
			requestSocket=socketObject;
		}

		@Override
		public void run() {
			try {
				DataInputStream dataIs=new DataInputStream(requestSocket.getInputStream());
				DataOutputStream dataOs=new DataOutputStream(requestSocket.getOutputStream());
				int cmd=dataIs.readInt();
				String message=cmd==0?"Put ":"Get ";
				String fileName=dataIs.readUTF();
				message+=fileName+" REQUEST";
				fileName="C:/Documents and Settings/Administrator/桌面/Server.txt";
				if (cmd==0) {
					uploadFile(dataIs,fileName);
				}else {
					downFile(dataOs,fileName);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}

		private void uploadFile(DataInputStream dataIs, String fileName) {
			try {
				BufferedWriter writer=new BufferedWriter(new FileWriter(fileName));
				String tempStr;
				while (!(tempStr=dataIs.readUTF()).equals("-1")) {
					writer.write(tempStr);
					writer.newLine();
				}
				writer.close();
				dataIs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		private void downFile(DataOutputStream dataOs, String fileName) {
			try {
				BufferedReader reader=new BufferedReader(new FileReader(fileName));
				String tempStr=null;
				while ((tempStr=reader.readLine())!=null) {
					dataOs.writeUTF(tempStr);
				}
				dataOs.writeUTF("-1");
				dataOs.close();
				reader.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
---------

StorgeClientSample

public class StorgeClientSample {
	
	public static void main(String[] args) {
		
		int cmd=1;
		try {
			Socket requestScoket=new Socket();
			requestScoket.connect(new InetSocketAddress("localhost",8080));
			if (cmd==0) {
				String fileName="C:/Documents and Settings/Administrator/桌面/Test.txt";
				BufferedReader reader=new BufferedReader(new FileReader(fileName));
				DataOutputStream dataOs=new DataOutputStream(requestScoket.getOutputStream());
				dataOs.writeInt(cmd);
				dataOs.writeUTF(fileName);
				String tempStr;
				while ((tempStr=reader.readLine())!=null) {
					System.out.println(tempStr);
					dataOs.writeUTF(tempStr);
				}
				dataOs.writeUTF("-1");
				dataOs.close();
				reader.close();
			}else {
				String fileName="C:/Documents and Settings/Administrator/桌面/Down.txt";
				BufferedWriter writer=new BufferedWriter(new FileWriter(fileName));
				DataOutputStream dataOs=new DataOutputStream(requestScoket.getOutputStream());
				dataOs.writeInt(cmd);
				dataOs.writeUTF(fileName);
				DataInputStream dataIs=new DataInputStream(requestScoket.getInputStream());
				String tempStr;
				while (!(tempStr=dataIs.readUTF()).equalsIgnoreCase("-1")) {
					System.out.println(tempStr);
					writer.write(tempStr);
					writer.newLine();
				}
				dataIs.close();
				writer.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
---------

>创建多电波服务器和客户端

---------

StockTradesServer

/**
 * 	@author Lean  @date:2014-10-11  
 */
public class StockTradesServer {
	
	public static void main(String[] args) {
		Thread stockSThread=new Thread(new StockTradeGenerator());
		stockSThread.setDaemon(true);
		stockSThread.start();
		try {
			Thread.sleep(30000);
		} catch (InterruptedException e) {
		}
	}
	
	static class StockTradeGenerator implements Runnable{
		
		private DatagramSocket broadcastSocket;
		private String[] stockSymbols ={"IBM","SNE","XRX","MHP","NOK"};
		
		public StockTradeGenerator() {
			try {
				broadcastSocket=new DatagramSocket(4445);
			} catch (SocketException e) {
				System.out.println("error create socket ! ");
			}
		}
		
		@Override
		public void run() {
			byte[] buff=new byte[126];
			try {
				while (true) {
					int index=(int) (Math.random()*5);
					float trade=generatorRandomTrade(index);
					String tempStr=String.format("%s %.2f@ %s",stockSymbols[index],trade,now());
					buff=tempStr.getBytes();
					InetAddress groupInetAddresses;
						groupInetAddresses = InetAddress.getLocalHost();
					DatagramPacket datagramPacket=new DatagramPacket(buff,buff.length, groupInetAddresses,4446);
					broadcastSocket.send(datagramPacket);
					Thread.sleep(500);
				}
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally{
				broadcastSocket.close();
			}
		}
		
	}

	public static float generatorRandomTrade(int index) {
		float trade=(float) Math.random();
		switch (index) {
			case 0:
				trade+=118;
				break;
			case 1:
				trade+=29;
				break;
			case 2:
				trade+=8;
				break;
			case 3:
				trade+=26;
				break;
			case 4:
				trade+=14;
				break;
			default:
				break;
		} 
		return trade;
	}

	public static Object now() {
		SimpleDateFormat df=new SimpleDateFormat("HH:mm:ss");
		Date date=new Date();
		return df.format(date);
	}
	
}
---------

StockTradeClient

/**
 * 	@author Lean  @date:2014-10-11  
 */
public class StockTradeClient {

	public static void main(String[] args) throws IOException {
		MulticastSocket multicastSocket=new MulticastSocket(4446);
		InetAddress address=InetAddress.getByName("232.0.1.1");
		multicastSocket.joinGroup(address);
		for (int i = 0; i < 10; i++) {
			byte[] buff=new byte[256];
			DatagramPacket datagramPacket=new DatagramPacket(buff,buff.length);
			multicastSocket.receive(datagramPacket);
			System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
		}
		multicastSocket.leaveGroup(address);
		multicastSocket.close();
	}
	
}
---------


分享到:
评论

相关推荐

    Java进阶-JDBC(八).zip

    本资料包"Java进阶-JDBC(八)"可能包含了一系列关于JDBC深入理解和实践的教程,特别是针对MySQL数据库的使用。 在JDBC中,主要涉及以下几个核心概念: 1. **Driver Manager**:Java中的`java.sql.DriverManager`...

    java进阶篇课后编程习题答案

    "Java进阶篇课后编程习题答案"提供了针对Java高级概念的练习题解答,旨在帮助学习者深入理解Java语言的核心特性,提升编程技能。下面将详细阐述Java进阶中的关键知识点,并结合课后习题可能涉及的内容进行解析。 1....

    Android高级进阶--免解压密码

    四、JNI与C/C++编程 为了提高性能,有时需要使用JNI(Java Native Interface)调用C/C++代码来处理文件。本书将讲解JNI的基本概念、如何编写本地方法、如何编译链接库,以及如何在Java代码中调用这些本地方法。这...

    黑马程序员-Java语言进阶-源码、教程笔记.zip

    day01_Object类、常用API day02_Collection、泛型 day03_List、Set、数据结构、Collections day04_Map,斗地主案例 ...day11_网络编程 day12_函数式接口 day13_Stream流、方法引用 Java基础小节练习题答案

    JavaSE进阶-01-面向对象.pdf

    在Java编程语言中,面向对象特性是其核心概念之一,本资料主要讲解了JavaSE进阶中的面向对象相关知识,包括final关键字、抽象类、接口、抽象类与接口的区别、Object类、package和import以及访问权限控制。...

    Java进阶学习网络服务器编程.rar

    在Java进阶学习网络服务器编程的过程中,我们将会深入探讨如何使用Java语言来构建高效、可靠的网络应用程序和服务。网络服务器编程是软件开发中的一个重要领域,它涉及到客户端与服务器之间的通信,数据传输,以及...

    Java进阶学习资料.zip

    以上只是Java进阶学习的部分核心知识点,实际的学习过程中,还应结合实际项目经验,通过阅读源码、参与开源项目等方式,持续提升自己的编程技能和问题解决能力。"Java进阶学习资料.zip"这个压缩包可能包含了相关的...

    编程实践:Java进阶100例

    ●本书是作者多年来教学实践经验的总结,汇集了学员在学习课程或认证考试中遇到的概念、操作、应用等问题及解决方案 ●针对Java SE 8新功能全面改版,无论是章节架构或范例程序代码,都做了重新编写与全面翻新

    程序员编程指南 - Java、Spring、SpringBoot等等基础-进阶-源码知识点 & 面试宝典 - 建议使用Obsi

    《程序员编程指南》是一份全面涵盖Java、Spring和SpringBoot等技术的基础到进阶的知识宝典,特别适合希望深入理解并提升技能的开发者。这份资料不仅包含基础编程概念,还涉及高级特性和源码分析,旨在帮助程序员在...

    java进阶13天资料.zip

    Java进阶13天资料 day01-复习回顾、静态、继承、引用类型使用 day02-抽象类、接口、代码块,final、单例、枚举 day03-多态、包、权限修饰符、内部类,Object类,Date类 day04-常用API、正则表达式,泛型、Collection...

    Java进阶编程(经典网帖合集)

    以下是一些重要的Java进阶编程知识点,它们涵盖了多个方面,包括面向对象、多线程、集合框架、异常处理、JVM优化、网络编程以及高级设计模式等。 1. **面向对象编程**:Java是一种完全面向对象的编程语言,理解类、...

    JavaSE进阶-08-反射机制1

    Java SE 进阶课程中的反射机制是编程中的一个重要主题,尤其对于那些希望编写更加灵活和动态的代码的开发者来说。反射机制允许程序在运行时获取关于类、接口、字段和方法的信息,并能直接操作它们,这在许多高级编程...

    基于Java进阶知识的编程实践设计源码

    本项目为基于Java进阶知识的综合性编程实践设计源码,包含220个文件,涵盖141个Java源代码文件、35个XML配置文件、17个Markdown文档、15个YAML配置文件、4个SQL数据库脚本、1个Git忽略规则文件、1个开源许可证文件,...

    Java进阶100例

    《Java进阶100例》是一本专为Java初学者设计的学习教程,旨在帮助从零开始的人系统地掌握Java编程技术。这个压缩包包含了"编程实践:Java进阶100例.pdf"这一核心资料,它将通过一系列具体实例,深入浅出地讲解Java...

    Java7编程高级进阶

    Java进阶必备,适合有一定基础的Java开发者。Java进阶必备,适合有一定基础的Java开发者。

    java进阶篇主要内容的PPT

    本PPT详细阐述了Java进阶学习的关键概念和技术,旨在帮助读者深化对Java编程的理解,提升开发技能。这个资料涵盖了不仅限于教科书的知识,确保你能够掌握到实际工作中可能遇到的实用技巧和高级特性。 **1. 高级数据...

    Java进阶.zip

    "Java进阶"这个主题涵盖了Java开发中的高级概念和技术,旨在帮助程序员深入理解Java的精髓,提升开发技能。SunJava.pdf可能包含的是由Sun Microsystems(Java的原始开发者)发布的官方文档或教程。 1. **内存管理与...

Global site tag (gtag.js) - Google Analytics