发送端源码:
package com.dyn.itheima.test9;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class SendData implements Runnable {
private DatagramSocket datagramSocket = null;
private DatagramPacket packet = null;
// 创建构造函数,接收数据报包套接字
public SendData(DatagramSocket datagramSocket) {
this.datagramSocket = datagramSocket;
}
@Override
public void run() {
// TODO Auto-generated method stub
// 键盘录入数据
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
// 声明变量接收数据
String data = null;
byte[] buf = new byte[1024];
// 读取数据
try {
while ((data = reader.readLine()) != null) {
buf = data.getBytes();
packet = new DatagramPacket(buf, buf.length,
InetAddress.getByName("127.0.0.1"), 10086);
datagramSocket.send(packet);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(datagramSocket.isClosed()){
datagramSocket.close();
}
}
}
}
接收端:
package com.dyn.itheima.test9;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class RecieveData implements Runnable {
//创建数据报包套接字和数据报包
private DatagramSocket datagramSocket = null;
private DatagramPacket packet = null;
public RecieveData(DatagramSocket datagramSocket) {
this.datagramSocket = datagramSocket;
}
@Override
public void run() {
// TODO Auto-generated method stub
//创建接收数据所需变量
byte[] buf = new byte[1024];
String ip = null;
String data = null;
while (true) {
packet = new DatagramPacket(buf, buf.length);
try {
//接收数据
datagramSocket.receive(packet);
//解封数据
ip = packet.getAddress().getHostName();
data = new String(packet.getData(), 0, packet.getLength());
//输出结果
System.out.println("来自 " + ip + " 的数据为 " + data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
公共聊天室:
package com.dyn.itheima.test9;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ChatRoom {
public static void main(String[] args) {
//声明接收和发送端数据报包套接字
DatagramSocket send = null;
DatagramSocket recieve = null;
try {
//实例化接收和发送端数据报包套接字
send = new DatagramSocket();
recieve = new DatagramSocket(10086);
//开启发送和接收端线程
new Thread(new SendData(send)).start();
new Thread(new RecieveData(recieve)).start();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭发送端
if(send.isClosed()){
send.close();
}
//关闭接收端
if(recieve.isClosed()){
recieve.close();
}
}
}
}
总结:
由于本人技术有限,代码中可能存在不合理的地方,望大家积极讨论,点评。
|
|