62,620
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Server extends JFrame {
ServerSocket ser;
Socket con;
ObjectOutputStream salida;
ObjectInputStream entrada;
public Server() {
}
void ejecutar(){
try{
ser = new ServerSocket( 5700,1 );
con = ser.accept();
salida = new ObjectOutputStream(con.getOutputStream());
salida.flush();
entrada = new ObjectInputStream(con.getInputStream());
procesar();
}
catch(IOException e){}
}
void procesar(){
while(true){
try{
JFileChooser fc=new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int r = fc.showOpenDialog(this);
File f = fc.getSelectedFile();
salida.writeObject( new ImageIcon(""+f) );
}catch(IOException e){}
}
}
public static void main(String args[]) {
Server srv = new Server();
srv.ejecutar();
}
}
Client:
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Cliente extends JFrame {
JTextField tf;
Lienzo lienzo;
Socket con;
ObjectOutputStream salida;
ObjectInputStream entrada;
public Cliente(){
super("Cliente");
Container c = getContentPane();
tf = new JTextField(10);
lienzo=new Lienzo();
c.add(lienzo);
pack();
setSize(100,100);
setVisible(true);
}
void ejecutar(){
try{
con = new Socket("127.0.0.1",5700);
salida = new ObjectOutputStream(con.getOutputStream());
salida.flush();
entrada = new ObjectInputStream(con.getInputStream());
procesar();
}
catch(IOException e){}
}
void procesar() throws IOException {
try{
while(true){
ImageIcon img = (ImageIcon) entrada.readObject();
escribir(img);
}
}catch(ClassNotFoundException e){}
}
void escribir(final ImageIcon img){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
lienzo.pinta(img);
}
}
);
}
public static void main( String args[] ){
Cliente cl = new Cliente();
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.ejecutar();
}
class Lienzo extends JPanel{
ImageIcon img=null ;
public Lienzo(){
}
public void pinta(ImageIcon img){
this.img=img;
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(img!=null)
img.paintIcon(this,g,10,10);
}
}
}