黑马程序员_14Udp实例

来源:互联网 发布:淘宝店铺开通了 编辑:程序博客网 时间:2024/06/05 00:47
------- android培训ios培训、期待与您交流! ----------
//客户端程序
import java.net.*;
import java.io.*;
public class UdpClient{
 public static void main(String[] args) throws Exception{
 
  long l = 10000L;

  ByteArrayOutputStream baos = new ByteArrayOutputStream();

  DataOutputStream dos = new DataOutputStream(baos);
  dos.writeLong(l);
  byte[] buf1 = baos.toByteArray();
/*程序明明写对了,就是结果不对,最后发现时IP填写错误,由于电脑自动获得IP,所以IP地址发生改变,忘记修改这里的ip地址,最后导致客户端与服务端没有成功对接*/
  DatagramPacket dp = new DatagramPacket(buf1,buf1.length,new    InetSocketAddress("192.168.1.102",5678));
 
  //需要研究一下
  DatagramSocket ds = new DatagramSocket(9999);
  ds.send(dp);
  ds.close();
 }
}
//服务器端程序
import java.net.*;
import java.io.*;
public class UdpServer{
 public static void main(String[] args){
  byte[] buf = new byte[1024];
  DatagramPacket dp = new DatagramPacket(buf,buf.length);
  try{
  DatagramSocket ds = new DatagramSocket(5678);
   while(true){
    ds.receive(dp);
    ByteArrayInputStream dais = new ByteArrayInputStream(buf,0,buf.length);
    DataInputStream dis = new DataInputStream(dais);
    long l =dis.readLong();
    System.out.println("为什么出不来呢");
    System.out.println(l);
  }catch(SocketException e){
   System.out.println("error");
   e.printStackTrace();
  }catch(IOException e){
   e.printStackTrace();
  }
 }
}

编程总结:
1、首先需要构建客户端与服务端连接的通道,这里主要是使用的是DatagramSocket 类来实现,数据在发送之前,需要进行打包处理
2、可以发送的数据需要使用byte[] 数组进行存储,然后进行流包装,需要发long double等类型的数据时,可以用DataOutputStream等数据流进行包装
3、构建服务器端与客户端的通信时,需要注意指定的地址是否正确,不然即使程序正确了,也得不到自己想要实现的效果,因为发送数据域接收数据没有有效建立连接
0 0
原创粉丝点击