黑马程序员 java UDP DatagramSocket Thread Runnable 模拟qq聊天

来源:互联网 发布:淘宝五钻店铺值多少钱 编辑:程序博客网 时间:2024/05/07 05:36
package itcast.video.network;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;


public class I_02_UDP_Demo {


/**
* UDP协议传输数据

* @param args
*/
public static void main(String[] args) throws Exception {


DatagramSocket send = new DatagramSocket();
DatagramSocket receive = new DatagramSocket(10000);
new Thread(new Send(send)).start();
new Thread(new Receive(receive)).start();
}





}


class Send implements Runnable {
private DatagramSocket ds;


public Send(DatagramSocket ds) {
this.ds = ds;
}


@Override
public void run() {
BufferedReader bw = null;
try {
bw = new BufferedReader(new InputStreamReader(System.in));
DatagramPacket dp = null;
String line = null;
int len = 0;
byte[] buf = null;
while ((line = bw.readLine()) != null) {
if ("886".equals(line))
break;
buf = line.getBytes();
dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("127.0.0.1"), 10000);
ds.send(dp);


}
} catch (Exception e) {
e.printStackTrace();
} finally {


try {
if (bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null)
ds.close();
}


}
}
}


class Receive implements Runnable {
private DatagramSocket ds;


public Receive(DatagramSocket ds) {
this.ds = ds;
}


@Override
public void run() {
try {
DatagramPacket dp = null;
String line = null;
int len = 0; 
byte[] buf = new byte[1024];
while (true) {
dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String address = dp.getAddress().getHostAddress();
line = new String(dp.getData(),0,dp.getLength());
System.out.println(address+"  :  "+line);


}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ds != null)
ds.close();
}
}
}
0 0