目前在 准备博客,云4,这个月有点难度。。晒下。给自己一下鼓励
/*
* 聊天程序
* 有接受数据的部分和发数据的部分
* 并且同时执行
* 多线程技术
* 因为收数据和发数据是不一致的,所有要定义两个run方法,所以要有两个类
*/
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;
/**
*
* @author Administrator
*
*/
public class Chat {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
DatagramSocket sendsocket = new DatagramSocket();
DatagramSocket recesocket = new DatagramSocket(10001);
Thread t1 = new Thread(new Send(sendsocket));
Thread t2 = new Thread(new Rece(recesocket));
t1.start();
t2.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 发送端类
*
* @author Administrator
*
*/
class Send implements Runnable {
private DatagramSocket ds;
public Send(DatagramSocket ds) {// 初始化一个发送端DatagramSocket对象
this.ds = ds;
}
public void run() {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));// 键盘录入
try {
String line = null;
while ((line = br.readLine()) != null) {// 循环读取
if (line.equals("86"))
break;
// 构造数据包,封装了数据,接受ip,接受端口,存储数据
byte[] b = line.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length, InetAddress
.getByName("192.168.1.100"), 10001);
ds.send(dp);
}
} catch (Exception e) {
// TODO Auto-generated catch block
try {
throw new Exception("发送端失败");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
ds.close();
}
}
}
/**
* 接受端类
*
* @author Administrator
*
*/
class Rece implements Runnable {
private DatagramSocket ds;
public Rece(DatagramSocket ds) {// 初始化一个接受端DatagramSocket对象
this.ds = ds;
}
@Override
public void run() {// 重写线程run方法
// TODO Auto-generated method stub
while (true) {
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
try {
ds.receive(dp);// 阻塞式方法
// 通过数据包获取ip,和转换后的字符串
String ip = dp.getAddress().getHostName();
String data = new String(dp.getData(), 0, dp.getLength());
System.out.println("ip" + ip + "data" + data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|