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


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。