日期:2014-05-20  浏览次数:20778 次

一道第三届itatjava复赛试题
编写客户/服务器程序,客户端Client.java使用DatagramSocket对象将数据包发送到服务器,请求获取服务器端的图像(考生可自选图像文件)。服务器端Server.java将图像文件包装成数据包,并使用DatagramSocket对象将该数据包发送到客户端。首先将服务器端的程序编译通过,并运行起来,等待客户的请求。(本题30分)
要求在在客户端造一个frame,frame上有个button,待年级按钮,显示图片。
服务器段输出客户端的ip。

这是我的程序,不能在淡季按钮时显示出图片。

import java.net.*;
import java.io.*;
import java.util.*;


public class Server extends Thread{
protected DatagramSocket ds=null;
protected BufferedReader br=null;
protected boolean ismore=true;
public Server() throws Exception
{
this("Server");
}
public Server(String name) throws Exception
{
super(name);
ds=new DatagramSocket(5432);
}
public void run()
{
try{
byte[] buf=new byte[256];
DatagramPacket dp=new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ss=null;
ss="tt/gg.jpg";
buf=ss.getBytes();
InetAddress address=dp.getAddress();
int port=dp.getPort();
System.out.println("客户端的地址:"+address);
dp=new DatagramPacket(buf,buf.length,address,port);
ds.send(dp);
ds.close();
}catch(Exception ex)
{
ex.toString();
}

}
  public static void main(String[] args) throws Exception
  {
new Server().start();
  }
}

import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;

public class Client extends Frame implements MouseListener,WindowListener{
Frame frame1=new Frame("I am a client");
JButton bt1;
JLabel l1;
String ss=null;
//Image img=null;
 
public void go()
{
frame1.setLayout(null);
bt1=new JButton("获取图像");
bt1.setBounds(50,30,200,40);
frame1.add(bt1);
// l1=new JLabel("hello");
// l1.setBounds(50, 80, 200, 250);
// frame1.add(l1);
bt1.addMouseListener(this);
frame1.addWindowListener(this);
frame1.setSize(300,300);
frame1.setVisible(true);
}

public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e)
{
try{
DatagramSocket ds=new DatagramSocket();
byte[] buf=new byte[256];
InetAddress address=InetAddress.getByName("127.0.0.1");
DatagramPacket dp=new DatagramPacket(buf,buf.length,address,5432);
ds.send(dp);
dp=new DatagramPacket(buf,buf.length);
ds.receive(dp);
String recevied=new String(dp.getData());
Icon con = new ImageIcon(recevied);
l1=new JLabel(con);
l1.setBackground(Color.blue);
l1.setBounds(50, 80, 200, 250);
frame1.add(l1);
  ds.close();
}catch(Exception ex)
{
ex.toString();
}
}

public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowClosing(WindowEvent e)
{
System.exit(1);
}

  public static void main(String[] args)
  {
  Client f=new Client();
  f.go();
 
 
  }
}

------解决方案--------------------
按钮还是用ActionListener吧
------解决方案--------------------