第一题:udp传输屏幕广播(低于64k)。 import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.ImageIcon; import java.net.DatagramPacket; import java.net.DatagramSocket; class ClientDemo{ public static void main(String[] args) throws Exception{ ClientUI ui = new ClientUI(); new ClientReceive(ui).start(); } } class ClientUI extends JFrame{ private JLabel label; private ImageIcon icon; public ClientUI(){ ini(); } public void ini(){ this.setBounds(0,0,600,400); this.setLayout(null); label = new JLabel(); label.setBounds(0,0,600,400); label.setLayout(null); icon = new ImageIcon("e:/a.png"); label.setIcon(icon); this.add(label); this.setVisible(true); } public void refreshImage(byte[] image_arr){ label.setIcon(new ImageIcon(image_arr)); } } class ClientReceive extends Thread{ private DatagramSocket socket; private ClientUI ui; public ClientReceive(ClientUI ui) throws Exception{ this.ui = ui; socket = new DatagramSocket(8889); } public void run(){ try{ int i = 0; while(true){ byte[] buf = new byte[1024*60]; DatagramPacket packet = new DatagramPacket(buf,buf.length); socket.receive(packet); int length = packet.getLength(); ui.refreshImage(buf); Thread.sleep(1000); } }catch(Exception e){ e.printStackTrace(); } } } import java.net.DatagramSocket; import java.net.DatagramPacket; import java.net.InetAddress; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.awt.Robot; import javax.imageio.ImageIO; import java.io.FileOutputStream; import java.io.ByteArrayOutputStream; import java.util.zip.GZIPOutputStream; class ServerDemo{ public static void main(String[] args) throws Exception{ DatagramSocket socket = new DatagramSocket(8888); int i = 0; while(true){ byte[] buf = null; buf = new byte[1024*60]; Rectangle rect = new Rectangle(0,0,600,400); BufferedImage image = (new Robot()).createScreenCapture(rect); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image,"jpg",baos); byte[] zipData = baos.toByteArray(); DatagramPacket packet = new DatagramPacket(zipData,zipData.length); InetAddress addr = InetAddress.getByName("127.0.0.1"); packet.setAddress(addr); packet.setPort(8889); socket.send(packet); i++; Thread.sleep(1000); System.out.println(i); } } }
本文出自 “森林敏” 博客,请务必保留此出处http://senlinmin.blog.51cto.com/6400386/1790128
原文地址:http://senlinmin.blog.51cto.com/6400386/1790128