package 聊天;
/*一切随便消逝吧*/
import java.net.DatagramSocket;
import java.net.SocketException;
public class ChatDemo {
public static void main(String[] args) throws Exception {
DatagramSocket send=new DatagramSocket();
DatagramSocket rece=new DatagramSocket(10001);
new Thread(new Send(send)).start();
new Thread(new Rece(rece)).start();
}
}
/*总结
* 第一步建立字节套服务。Socket
* 第二封装包 datagrampack
* 处理数据包
* 结束
*
*
* */
package 聊天;
/*
* udp接收端 建立udp socket 创建数据包,用于存储接收到的数据。方便用数据包对象的方法解析这些数据
* 使用socket服务的receive方法将接收到得数据储存到数据包中 通过数据包的方法解析数据包中德数据。 关闭资源
*
*/
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Rece implements Runnable {
private DatagramSocket ds;
public Rece(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
while (true)
{
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String text = new String(dp.getData(), 0, dp.getLength());
System.out.println(dp.getAddress().getHostAddress()+":::"+text);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package 聊天;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/*
* 创建UDP传输的发送端 思路:建立udp的socket服务器 将要发送的数据封装到数据包中 通过udp的socket服务将数据包发送出去 关闭服务
*
*/
public class Send implements Runnable {
private DatagramSocket ds;
public Send(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = bf.readLine()) != null) {
byte[] buf = line.getBytes();
// 使用DatagramPacket封装数据
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 10001);
ds.send(dp);
if("886".equals(line)){
break;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
ds.close();
e.printStackTrace();
}
}
}