- //package jichu;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- class Tests {
- public static void main(String[] args) {
- new Thread(new Runnable() {
- public void run() {
- new Rec().recive();
- }
- }).start();
- new Thread(new Runnable() {
- public void run() {
- new Send().send();
- }
- }).start();
- }
- }
- class Send {
- public static void send() {
- DatagramSocket dSocket = null;
- BufferedReader bReader = new BufferedReader(new InputStreamReader(
- System.in));
- while (true) {
- try {
- dSocket = new DatagramSocket();
- } catch (SocketException e) {
- e.printStackTrace();
- }
- String string = null;
- DatagramPacket dPacket = null;
- try {
- string = bReader.readLine();
- } catch (IOException e) {
- e.printStackTrace();
- }
- byte[] buf = string.getBytes();
- try {
- dPacket = new DatagramPacket(buf, 0, buf.length,
- InetAddress.getLocalHost(), 10002);
- } catch (UnknownHostException e) {
- e.printStackTrace();
- }
- try {
- dSocket.send(dPacket);
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (string.equals("over")) {
- break;
- }
- }
- dSocket.close();
- try {
- bReader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- class Rec {
- public static void recive() {
- String string = null;
- DatagramSocket dSocket = null;
- try {
- dSocket = new DatagramSocket(10002);
- } catch (SocketException e1) {
- e1.printStackTrace();
- }
- DatagramPacket dPacket = null;
- while (true) {
- byte[] buf = new byte[1024];
- dPacket = new DatagramPacket(buf, 0, buf.length);
- try {
- dSocket.receive(dPacket);
- } catch (IOException e) {
- e.printStackTrace();
- }
- byte[] by = dPacket.getData();
- //string = new String(by, 0, by.length);
- string=new String(dPacket.getData(),0,dPacket.getLength());
- System.out.println("receive:"+string);
- if (string.equals("over")) {
- break;
- }
- }
- dSocket.close();
- }
- }
复制代码 我的运行结果如下:
|