package 网络编程.UDP网络编程;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPRTest {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//创建UDP服务
DatagramSocket ds = new DatagramSocket(10005);//接收方监听的端口号
//定义数据格式
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf , buf.length);
//接收数据
while(true){
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
int port = dp.getPort();
System.out.println(ip+":"+port+":"+data);
}
}
}
package 网络编程.UDP网络编程;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPNetTest {
public static void main(String[] args) throws Exception{
//创建UDP服务
DatagramSocket ds = new DatagramSocket(8889);//UDP发送方的端口号
//创建要发送的数据
byte[] buf = "hello world!".getBytes();
DatagramPacket dp = new DatagramPacket(buf , buf.length, InetAddress.getByName("localhost"),10005);//发往对方的地址和对方接收的端口号
//发送
while(true ){
Thread.sleep(1000);
ds.send(dp);
}
}
}
package 网络编程.多线程和UDP实现聊天功能;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* 聊天室:一个线程控制收数据,一个线程控制发数据
* 因为收和发数据时不一致的,所有要定义两个run方法,所以要定义两个
* @author Administrator
*
*/
public class ChatRoom {
public static void main(String[] args) throws Exception{
DatagramSocket sendDs = new DatagramSocket();
DatagramSocket recds = new DatagramSocket(9990);
Send send = new Send(sendDs);
Receiver re = new Receiver(recds);
new Thread(send).start();
new Thread(re).start();
}
}
class Send implements Runnable{
private DatagramSocket ds;
Send(DatagramSocket ds){
this.ds = ds;
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = br.readLine())!=null){//while循环,保证此线程在特定情况下不死
if("886".equals(line))
break;
byte[] buff = line.getBytes();
DatagramPacket dp =
new DatagramPacket(buff, buff.length, InetAddress.getByName("192.168.0.255"), 9990);
ds.send(dp);
}
} catch (Exception e) {
throw new RuntimeException("发送端异常");
}
}
}
class Receiver implements Runnable{
private DatagramSocket ds;
Receiver(DatagramSocket ds){
this.ds = ds;
}
public void run() {
try {
while(true){//while循环,保证此线程不死
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String data = new String(dp.getData() , 0 , dp.getData().length);
System.out.println(ip+":"+port+"说:"+data);
}
} catch (Exception e) {
throw new RuntimeException("接收失败");
}
}
}原文地址:http://blog.csdn.net/u010218226/article/details/45175755