• JAVA进阶-网络编程


    >通过套接字连接server
    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
    
    ".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;
    		}
    		
    	}
    	
    }
    
    ---------
    >编写同一时候服务多个client的server程序
    ---------
    /**
     * 	@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();
    			}
    		}
    	}
    	
    }
    
    ---------
    >编写实际的文件存储server程序
    ---------

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

    >创建多电波server和client

    ---------

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

    网络基础知识(转)

    Ip:提供了数据的发送地址和接收地址;位于网络层;
    Tcp:三次握手,"带重定向的肯定确认"技术来实现传输可靠性,"滑动窗体"的流量控制
    对Ip包进行解包,并对分解的tcp包进行排序,假设出错,即发出又一次请求的信号
    Udp:面向无连接的传输数据协议,可当做广播处理,不监控包的顺序,速度快,easy产生丢包现象;
    Icmp:为ip指出通向目标地址的路径信息.

    通讯port:以源地址源port,目标地址目标port作为确定,并依靠传输层协议对每次传输进行确认 

    数据格式:帧头+IP数据包+帧尾(帧头包含源和目标主机MAC地址及类型,帧尾是校验字)
    IP数据包:IP头部+TCP数据信息(IP头包含源和目标主机IP地址、类型、生存期等)
    TCP数据信息:TCP头部+实际数据 (TCP头包含源和目标主机port号、顺序号、确认号、校验字等)


    网络接口层:数据链路层是负责接收IP数据包并通过网络发送,
    或者从网络上接收物理帧,抽出IP数据包,交给IP层。
    网络层:装载和分解IP数据包 进行流控,地址转换,路径处理等等。
    传输层:格式化数据流并检查错误。实现错误则又一次请求。

    OSI/RM(开放系统互联/參考模型)
    1) 物理层
    对数据链路层提供物理介质连接,包含激活,维持,去活物理连接。
    2) 数据链接层
    传送以祯为单位的数据,并对容错,流控进行管理
    3) 网络层
    对网络提供建立维持终止等连接手段。最重要的是网络选路和寻址
    4) 传输层
    屏蔽下层控制细节,并实现可靠的传输数据机制来收发报文。
    5) 会话层
    进程间的通讯,管理两个会话进程间的通讯。


    6) 表示层
    将数据的抽象语法转化为传送语法。

    对数据解压/加压等等。
    7) 应用层
    为用户应用进程訪问OSI提供接口,以满足用户的须要。

  • 相关阅读:
    日志配置
    Mybaties核心配置文件
    配置3
    写了两个数据获得方式----费劲周折
    applicationContext
    配置2
    Django-缓存的配置
    RabbitMQ的工作模式
    centos下保留python2安装python3
    python位运算
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/6842589.html
Copyright © 2020-2023  润新知