UDP通信实践

UDP(user datagram protocol用户数据报协议)通信实践<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

主要用到的类

 

DatagramSocket:用于接收,发送DatagramPacket

 

DatagramPacket:信息载体,指定ip和端口可以用DatagramSocket发送,不指定则用户接收数据包

 

InetAddress:网络地址(ip),InetAddress.getByName(null);获取本机地址(参数为域名或ip)

 

1.

 

package com.sk.udp;

 

 

import java.io.IOException;

 

import java.net.DatagramPacket;

 

import java.net.DatagramSocket;

 

import java.net.InetAddress;

 

import java.net.SocketException;

 

 

public class Sender {

 

private DatagramSocket ds;

 

private DatagramPacket dp;

 

 

 

public Sender() throws SocketException{

 

//创建socket实例,端口3333

 

ds=new DatagramSocket(3333);

 

 

}

 

public void send(String msg,String ip,int port) throws IOException{

 

byte[] buf=msg.getBytes();

 

//创建数据包,指定数据包存储地,长度,要发送的ip,端口

 

dp=new DatagramPacket(buf,buf.length,InetAddress.getByName(ip),port);

 

//发送数据包

 

ds.send(dp);

 

//创建空数据包准备接收数据

 

dp=new DatagramPacket(buf,buf.length);

 

//接收数据

 

ds.receive(dp);

 

System.out.println(new String(buf)+":"+dp.getAddress());

 

//关闭socket

 

ds.close();

 

}

 

public static void main(String[] args) {

 

try {

 

new Sender().send("msg", "192.168.1.103", 8888);

 

} catch (SocketException e) {

 

// TODO Auto-generated catch block

 

e.printStackTrace();

 

} catch (IOException e) {

 

// TODO Auto-generated catch block

 

e.printStackTrace();

 

}

 

}

 

}

 

2

 

package com.sk.udp;

 

 

import java.io.IOException;

 

import java.net.DatagramPacket;

 

import java.net.DatagramSocket;

 

import java.net.InetAddress;

 

import java.net.SocketException;

 

 

public class Receiver implements Runnable{

 

private DatagramSocket ds;

 

private DatagramPacket dp;

 

public Receiver() throws SocketException{

 

ds=new DatagramSocket(8888);

 

}

 

public String receive() throws IOException{

 

byte[] buf=new byte[1024];

 

dp=new DatagramPacket(buf,1024);

 

ds.receive(dp);

 

ds.close();

 

return new String(buf)+":"+dp.getAddress();

 

}

 

public void run() {

 

// TODO Auto-generated method stub

 

byte[] buf=new byte[1024];

 

System.out.println("ready");

 

 

 

try {

 

dp=new DatagramPacket(buf,1024);

 

ds.receive(dp);

 

InetAddress addr=dp.getAddress();

 

int port=dp.getPort();

 

 

dp=new DatagramPacket(buf,1024,addr,port);

 

ds.send(dp);

 

} catch (IOException e) {

 

// TODO Auto-generated catch block

 

e.printStackTrace();

 

}

 

 

}

 

 

public static void main(String[] args) {

 

try {

 

new Thread(new Receiver()).start();

 

} catch (SocketException e) {

 

// TODO Auto-generated catch block

 

e.printStackTrace();

 

}

 

}

 

}

 

 

你可能感兴趣的:(java,.net,socket,网络协议,Office)