黑马程序员技术交流社区
标题:
java基础:
[打印本页]
作者:
韩秀山
时间:
2013-5-14 20:54
标题:
java基础:
今天老师说:使用线程和Io流可以实现局域网聊天。谁能帮我做一个,要有详细的注释,说明每个语句的意思??谢谢大家了。。
作者:
尹丽峰
时间:
2013-5-14 21:10
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class duoxianchengliaotian
{
public static void main(String[]args) throws Exception
{
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket resceSocket = new DatagramSocket(10000);
send s = new send(sendSocket);
resce r = new resce(resceSocket);
Thread t1 = new Thread(s);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
class send implements Runnable {
private DatagramSocket ds;
public send(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
String line =null;
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
try {
while((line=bfr.readLine())!=null)
{
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.102"),10000);
ds.send(dp);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class resce implements Runnable
{
private DatagramSocket ds;
public resce(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
String line =null;
while(true)
{
byte[]buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
try {
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println(ip+":::"+data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//ds.close();
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2