网络编程
说了是两个端口,那么当然要创建两个项目,Client(客户端)和Server(服务端)。
创建窗口(服务端)
先看服务端,新建一个Frame类
Frame类
public class TestFrame extends JFrame {
TestPanel testPanel=new TestPanel();
public TestFrame() {
//窗口名字
super.setTitle("cxk");
//窗口大小
super.setSize(600,400);
//设置生成位置居中,即在屏幕中央
super.setLocationRelativeTo(null);
//设置关闭窗口时停止运行类
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.add(testPanel);
//窗口可视化
super.setVisible(true);
}
}
Panel类
public class TestPanel extends Panel {
BufferedImage image=null;
//读文件
public TestPanel(){
try {
File file=new File("6.png");
image= ImageIO.read(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void start() throws IOException {
ServerSocket serverSocket=new ServerSocket(6666);
while(true){
Socket socket=serverSocket.accept();
InputStream inputStream= socket.getInputStream();
image=ImageIO.read(inputStream);
repaint();
}
}
@Override
public void paint(Graphics g) {
g.drawImage(image,0,0,image.getWidth(),image.getHeight(),null);
}
}
测试类
public class TestM {
public static void main(String[] args) throws IOException {
TestFrame testFrame=new TestFrame();
testFrame.testPanel.start();
}
}
客户端
public class Test {
public static void main(String[] args) throws AWTException, IOException, InterruptedException {
//while(true) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
//截屏
BufferedImage image = robot.createScreenCapture(screenRectangle);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
ImageIO.write(image, "png", aos);
byte[] bytes = aos.toByteArray();
//127.0.01是指本地,可以换成自己的IP地址,6666是端口号,可随意输入
Socket socket = new Socket("127.0.0.1", 6666);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(bytes);
Thread.sleep(5);
outputStream.close();
socket.close();
// }
}
}
先运行服务端,再运行客户端,就会传过去一张截图
如果把while循环放开,可以进行类似于直播效果,实际上是写了一个死循环,让它一直截图,一直传