前言: UDP 方式传递数据分两个步骤 ,第一步 构建UDP 数据包 ,第二步 创建 UDP SOCKET
发送数据的时候: 构建UDP 数据包 需要写好 目的 IP 地址,以及目的主机的端口号
DatagramPacket data=new DatagramPacket(b,b.length,address,7000);
发送数据包 创建 SOCKET 可以不用指定端口号
DatagramSocket mailSend=new DatagramSocket();
接收数据的时候: 创建UDP 数据包不需要写IP 地址和端口号
pack=new DatagramPacket(b,b.length);
接收数据包时,创建SOCKET必须写端口号
mailReceive=new DatagramSocket(7000);
本例子是通过UDP 方式,从服务器端发送一幅图到客户端,客户端显示出来
编译后运行 java Server ,然后再开一个cmd 窗口 运行 java Client 。点击client 窗口的get picture 就可以了
注意 图片文件 a.jpg 需要和编译好的类放在一起。
/** *//**
* @(#)Server.java
*
* Server application
*
* @author
* @version 1.00 2007/4/16
*/
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;
System.out.println("server is running");
pack=new DatagramPacket(b,b.length);
try ...{
mailReceive=new DatagramSocket(7000);
System.out.println("socket build");
}
catch(IOException e)
...{
e.printStackTrace();
}
while(true)...{
try ...{
mailReceive.receive(pack);
address=pack.getAddress();
System.out.println("get client address:"+address);
}
catch(IOException e)...{
System.out.println("error is here");
}
if(address!=null)
...{
System.out.println("get address");
new ServerThread(address).start();
}
else
...{
System.out.println("can't get address");
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,b.length,address,5678);
DatagramSocket mailSend=new DatagramSocket();
mailSend.send(data);
System.out.println("read image");
}
in.close();
byte end[]="end".getBytes();
DatagramPacket data=new DatagramPacket(end,end.length,address,5678);
DatagramSocket mailSend=new DatagramSocket();
mailSend.send(data);
System.out.println("send all image data ok");
}
catch(Exception e)...{
e.printStackTrace();
}
}
}
转自:http://blog.csdn.net/pony1976bj/archive/2007/04/18/1568722.aspx
阅读(1098) | 评论(0) | 转发(0) |