主函数
package day25.word;
import java.net.DatagramSocket;
import java.net.SocketException;
import day25.ReceiveThread;
import day25.SendThread;
public class W1 {
/**
* @param args
* @throws SocketException
* @throws SocketException
* @throws SocketException
*/
public static void main(String[] args) throws SocketException {
// TODO Auto-generated method stub
DatagramSocket fds = new DatagramSocket();
DatagramSocket sds = new DatagramSocket(10000);
MySendThread st = new MySendThread(fds);
MyReceiveThread rt = new MyReceiveThread(sds);
Thread t1 = new Thread(st);
Thread t2 = new Thread(rt);
t1.start();
t2.start();
}
}
发送类
package day25.word;
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 MySendThread implements Runnable {
private DatagramSocket ds;
public MySendThread(DatagramSocket ds) {
this.ds = ds;
}
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));// 从键盘录入数据
String line = null;
while ((line = br.readLine()) != null) {
if ("886".equals(line)) {
break;
}
byte[] bys = line.getBytes();// 把每行数据封装成数据包
DatagramPacket dp = new DatagramPacket(bys, bys.length,
InetAddress.getByName("192.168.1.255"), 12580);
ds.send(dp); // 发送
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
ds.close();
}
}
}
接收类
package day25.word;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class MyReceiveThread implements Runnable {
private DatagramSocket ds;
public MyReceiveThread(DatagramSocket ds) {
this.ds = ds;
}
public void run() {
try {
while (true) {
byte[] bys = new byte[1024];// 创建数据包容器
DatagramPacket dp = new DatagramPacket(bys, bys.length);
ds.receive(dp);// 通过对象接收数据,把数据接收到数据包中
String ip = dp.getAddress().getHostAddress();// 解析数据
String data = new String(dp.getData(), 0, dp.getLength());
System.out.println(data + " from " + ip);
}
} catch (IOException e) {
e.printStackTrace();
}
finally {}
}
}
我这怎么不好使啊
|