java实验八 网络编程 (无脑实验系列)

1.读取服务器端文件。

²  实验要求:

创建一个URL对象,然后让URL对象返回输入流,通过该输入流读取URL所包含的资源文件。

package lzy;

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class ReadURLSource
{  
	public static void main(String args[])
   { 
	new NetWin();
   }
}

class NetWin extends Frame implements ActionListener,Runnable
{  
	Button button;

   URL url;
   TextField text;
   TextArea area; 
   byte b[]=new byte[118];
   Thread thread;
   NetWin()
   { 
	   text=new TextField(20);
      area=new TextArea(12,12);
      button=new Button("确定");
      button.addActionListener(this);
      thread=new Thread(this);
      Panel p=new Panel();
      p.add(new Label("输入网址:"));
      p.add(text); 
      p.add(button);
      add(area,BorderLayout.CENTER);
      add(p,BorderLayout.NORTH);
      setBounds(60,60,360,300);
      setVisible(true);
      validate();
      addWindowListener(new WindowAdapter()
                      {   public void windowClosing(WindowEvent e)
                           { 
                    	  System.exit(0);
                           }
                           
                      });
   }
   public void actionPerformed(ActionEvent e)
   { 
      if(!(thread.isAlive())) 
         thread=new Thread(this);
      try{
           thread.start();
         }
      catch(Exception ee)
         { text.setText("我正在读取"+url);
         }
   }
   public void run()
   {    try {    int n=-1;
                 area.setText(null);
                 String name=text.getText().trim();
                 url=new URL(name);    					//使用字符串name创建url对象
                 String hostName=url.getHost();     	//url调用getHost()
                 int urlPortNumber=url.getPort();      //url调用getPort() 
                 String fileName=url.getFile(); 		 //url调用getFile()
                 InputStream in=url.openStream();		//url调用方法返回一个输入流
                 area.append("\n主机:"+hostName+"端口:"+urlPortNumber+
"包含的文件名字:"+fileName);
                 area.append("\n文件的内容如下:");
                 while((n=in.read(b))!=-1)
                 {   String s=new String(b,0,n);
                     area.append(s);    
                 }
            }
          catch(MalformedURLException e1)
           {     text.setText(""+e1);
                 return;
           }
          catch(IOException e1)
           {     text.setText(""+e1);
                 return;
           }  
   }
}


2.使用套接字读取服务器端对象。

²  实验要求:

客户端将服务器端的文本区对象读取到客户端,并添加到窗口中。首先将服务器端的程序编译通过,并运行,等待客户的呼叫。

客户端模板:Client.java

//注意jdk版本问题。。。。太低就会报错。。。

package lzy;

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class Client extends Frame implements Runnable,ActionListener
{  Button connection;
   Socket socket=null;
   ObjectInputStream in=null; 
   ObjectOutputStream out=null;
   Thread thread; 
   public  Client()
   {  socket=new Socket();              
      connection=new Button("连接服务器,读取文本区对象");
      add(connection,BorderLayout.NORTH);
      connection.addActionListener(this);
      thread = new Thread(this);
      setBounds(100,100,360,310);
      setVisible(true);
      addWindowListener(new WindowAdapter()
                          { public void windowClosing(WindowEvent e)
                            {  System.exit(0);
                            }  
                          }
                       );
   }
   public void run()
   {  while(true)
       {   try{  TextArea text=(TextArea)in.readObject();  
                 add(text,BorderLayout.CENTER);
                 validate();
              }
           catch(Exception e) 
               { break;
               } 
       }
  }
  public void actionPerformed(ActionEvent e)
  { if(e.getSource()==connection)
    {  try
         {  if(socket.isConnected())
              {
              } 
            else
              { InetAddress  address=InetAddress.getByName("127.0.0.1");
                InetSocketAddress socketAddress=new  ServerSocket(4331);   //创建端口为4331、地址为address的socketAddress
                server.accept();    						//socket建立和socketAddress的连接呼叫。
             in =new ObjectInputStream(socket.getOutputStream()); 		//socket返回输入流
             out = new ObjectOutputStream(socket.getInputStream()); 	//socket返回输出流
                thread.start();
              }
         } 
        catch (Exception ee){}
    }
  }
  public static void main(String args[])
  {   
	  Client win=new  Client();
  }
}

服务器端模板:Server.java

package lzy;

import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
public class Server
{  public static void main(String args[])
   { 
	InetSocketAddress server=null;
      ServerThread thread;
      Socket you=null;
      while(true) 
       { 
    	  try{  
    	   server=new InetSocketAddress(address,4331);    //创建在端口4331上负责监听的 ServerSocket对象
              }
          catch(IOException e1) 
             {  System.out.println("正在监听");   
             } 
          try{  you=socket.connect(socketAddress);    // server返回和客户端相连接的Socket对象
                System.out.println("客户的地址:"+you.getInetAddress());
             }
         catch (IOException e)
             {  System.out.println("正在等待客户");
             }
         if(you!=null) 
             {  new ServerThread(you).start();  
             }
         else{  continue;
             }
      }
   }
}
class ServerThread extends Thread
{  Socket socket;
   ObjectInputStream in=null; 
   ObjectOutputStream out=null;
   String s=null;
   ServerThread(Socket t)
   {  socket=t;
      try  {
    	     out=new ObjectOutputStream(socket.getInputStream());    //socket返回输出流。
             in=new ObjectInputStream(socket.getOutputStream());      //socket返回输入流。
           }
      catch (IOException e)
          {}
   }  
   public void run()        
   {  TextArea text=new TextArea("你好,我是服务器",12,12);
      try{  out.writeObject(text);
         }
      catch (IOException e) 
         {   System.out.println("客户离开");
         }
   } 
}

3.基于UDP的图像传输。

²  实验要求:

编写客户/服务器程序,客户端使用DatagramSocket对象将数据包发送到服务器,请求获取服务器端的图像。服务器端将图像文件包装成数据包,并使用DatagramSocket对象将该数据包发送到客户端。首先将服务器端的程序编译通过,并运行起来,等待客户的请求。

客户端模板:Client.java

package lzy;

import java.net.*;
import java.awt.*; 
import java.awt.event.*;
import java.io.*;
class ImageCanvas extends Canvas
{ 
	Image image=null;
   public ImageCanvas()
   {  
	   setSize(200,200);
   }
   public void paint(Graphics g)
   { 
	   if(image!=null)
      g.drawImage(image,0,0,this);
   }
   public void setImage(Image image)
   {  
	   this.image=image;
   }
}
class Client extends Frame implements Runnable,ActionListener
{ 
	Button b=new Button("获取图像");
   ImageCanvas canvas;
   Client()
   { 
	   super("I am a client");
      setSize(320,200);
      setVisible(true);
      b.addActionListener(this);
      add(b,BorderLayout.NORTH);
      canvas=new ImageCanvas();
      add(canvas,BorderLayout.CENTER);
      Thread thread=new Thread(this);
      validate(); 
      addWindowListener(new WindowAdapter()
                          { public void windowClosing(WindowEvent e)
                            { System.exit(0);
                            }  
                          }
                       );
      thread.start();                              
   }
   public void actionPerformed(ActionEvent event)      
   { 
	   byte b[]="请发图像".trim().getBytes();
      try{   InetAddress address=InetAddress.getByName("127.0.0.1");
            DatagramPacket data=new DatagramPacket(b,b.length,address,1234); //创建数据包,该数据包的目标地址和端口分别是address和1234,其中的数据为数组b中的全部字节。
            DatagramSocket mailSend=new DatagramSocket(); //创建负责发送数据的DatagramSocket对象。
            mailSend.send(data);                   // mailSend发送数据data。
          }
      catch(Exception e){}     
   } 
  public void run()                              
   {
	  DatagramPacket pack=null;
      DatagramSocket mailReceive=null;
      byte b[]=new byte[8192];
      ByteArrayOutputStream out=new ByteArrayOutputStream();
      try{    
    	  pack=new DatagramPacket(b,b.length);
      mailReceive=new DatagramSocket(5678); //创建在端口5678负责收取数据包的DatagramSocket对象。
         }
      catch(Exception e){} 
      try{   while(true)   
              { 
    	  mailReceive.receive(pack); 
                 String gmessage=new String(pack.getData(),0,pack.getLength());
                 
                 if(gmessage.startsWith("end"))
                   { 
                	 break;
                   }
                 out.write(pack.getData(),0,pack.getLength());
              }
           byte imagebyte[]=out.toByteArray();
           out.close();
           Toolkit tool=getToolkit();
           Image image=tool.createImage(imagebyte);
           canvas.setImage(image);
           canvas.repaint();
           validate();
         }
      catch(IOException e){}
   }
 public static void main(String args[])
   {
	 new Client();
   }
}

服务器端模板:Server.java

package lzy;

import java.net.*;
import java.io.*;
public class Server
{ 
   public static void main(String args[])
   { 
	   DatagramPacket pack=null;
      DatagramSocket mailReceive=null;
      ServerThread thread;
      byte b[]=new byte[8192];
      InetAddress address=null;
      pack=new DatagramPacket(b,b.length);
       while(true) 
       {   try{ 
    	   mailReceive=new DatagramSocket(1234);//创建在端口1234负责收取数据包的
                                    //DatagramSocket对象。
              }
          catch(IOException e1) 
             { 
        	  System.out.println("正在等待");   
             } 
          try{   
        	  mailReceive.receive(pack); 
                address=pack.getAddress(); //pack返回InetAddress对象。
                System.out.println("客户的地址:"+address);
             }
         catch (IOException e) { }
         if(address!=null) 
             {  
        	 new ServerThread(address).start();   
             }
         else 
             {   continue;
             }
      }
   }
}
class ServerThread extends Thread
{  
	InetAddress address;
   DataOutputStream out=null;
   DataInputStream  in=null;
   String s=null;
   ServerThread(InetAddress address)
   {  this.address=address;
   }  
   public void run()                                
   {  
	   FileInputStream in;
      byte b[]=new byte[8192];
      try{  
    	   in=new  FileInputStream ("a.jpg");
            int n=-1;
            while((n=in.read(b))!=-1)
            {  DatagramPacket data=new DatagramPacket(b,n,address,5678);//创建数据包,目标地址和端口分别是address和5678,其中的数据为数组b中的前n个字节
              DatagramSocket mailSend=new DatagramSocket(); //创建发送数据的DatagramSocket对象
              mailSend.send(data);                   // mailSend发送数据data
            }
            in.close();
            byte end[]="end".getBytes();
            DatagramPacket data=new DatagramPacket(end,end.length,address,5678); //创建数据包,目标地址和端口分别是address和5678,其中的数据为数组end中的全部字节
            DatagramSocket mailSend=new DatagramSocket();//创建负责发送数据的DatagramSocket对象
            mailSend.send(data);                     // mailSend发送数据data
         }
      catch(Exception e){}
   }
}




  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值