import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
* 编写一个聊天程序。
* 有收数据和发数据
* 这两部分要同时执行,多线程技术,因为收和发是不一致的,所以要定义两个run方法,而且这两个方法要封装到不同类中
*
* @author Administrator
*
*/
public class Send implements Runnable{
private DatagramSocket ds;
public Send(DatagramSocket ds){
this.ds=ds;
}
@Override
public void run() {
try {
ds=new DatagramSocket();
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
String line=null;
while ((line=bufr.readLine())!=null) {
if ("886".equals(line)) {
break;
}
byte[] buf=line.getBytes();
DatagramPacket dp=new DatagramPacket(buf, buf.length,InetAddress.getByName("172.0.0.1"),1003);
ds.send(dp);
}
} catch (Exception e) {
}
}
}
class Rece implements Runnable{
private DatagramSocket ds;
public Rece(DatagramSocket ds){
this.ds=ds;
}
@Override
public void run() {
try {
while (true) {
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"::"+data);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
class ChatDemo{
public static void main(String[] args) throws Exception {
DatagramSocket sendSocket=new DatagramSocket();
DatagramSocket receSocket=new DatagramSocket(1003);
new Thread((Runnable)sendSocket).start();
new Thread((Runnable) receSocket).start();
}
}
3656

被折叠的 条评论
为什么被折叠?



