----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------
1,在一个局域网内通过192.168.1.255来实现局域网的聊天。
2,利用多线程来控制信息的发送和接受。
3,利用udp的特点来实现DatagramSocket的服务。
import java.io.*;
import java.net.*;
class DatagramSocketTest
{
public static void main(String[] args)throws Exception
{
DatagramSocket send = new DatagramSocket();
DatagramSocket receive = new DatagramSocket(8888);
new Thread(new SendClient(send)).start();
new Thread(new ReceiveClient(receive)).start();
}
}
class SendClient implements Runnable
{
private DatagramSocket dgs;
SendClient(DatagramSocket dgs)
{
this.dgs = dgs;
}
public void run()
{
BufferedReader bfr = null;
try
{
bfr = new BufferedReader(new InputStreamReader(System.in));
String st = null;
while ((st = bfr.readLine())!= null)
{
if("886".equals(st))
break;
byte[] buf = st.getBytes();
DatagramPacket agp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.100"),8888);
dgs.send(agp);
}
dgs.close();
}
catch (Exception e)
{
throw new RuntimeException("发送失败");
}
finally
{
try
{
if(bfr != null)
bfr.close();
}
catch (IOException e)
{
throw new RuntimeException("关闭流失败");
}
}
}
}
class ReceiveClient implements Runnable
{
private DatagramSocket dgs;
ReceiveClient(DatagramSocket dgs)
{
this.dgs = dgs;
}
public void run()
{
try
{
while (true)
{
byte[] buf = new byte[1024];
DatagramPacket agp = new DatagramPacket(buf,buf.length);
dgs.receive(agp);
String ip = agp.getAddress().getHostAddress();
String data = new String(agp.getData(),0,agp.getLength());
System.out.println("ip:" + ip + "--" + data);
}
}
catch (Exception e)
{
throw new RuntimeException("获取失败");
}
}
}
----------- android培训 、 java培训 、java学习型技术博客、期待与您交流! ------------