帮你改好了,其实这是因为你把所有数据都朝着8888这个端口给发了过去,而负责监听此端口的只有MyChat这一个。所以在初始化的时候,要把端口传。
import java.io.*;
import java.net.*;
class Send implements Runnable
{
private DatagramSocket ds;
private int num;
Send(DatagramSocket ds,int num)
{
this.ds = ds;
this.num=num;
}
public void run()
{
try
{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = bufr.readLine())!=null)
{
if("88".equals(line))
break;
byte[] by = line.getBytes();
DatagramPacket dp = new DatagramPacket(by,by.length,InetAddress.getByName("LocalHost"),num);
ds.send(dp);
}
}
catch (Exception e)
{
throw new RuntimeException("发送失败");
}
}
}
class Receive implements Runnable
{
private DatagramSocket ds;
Receive(DatagramSocket ds)
{
this.ds = ds;
}
public void run()
{
try
{
while(true)
{
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by,by.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
if("886".equals(data))
break;
System.out.println(ip+":"+data);
}
}
catch (Exception e)
{
throw new RuntimeException("接收失败");
}
}
}
class MyChat
{
public static void main(String[] args) throws Exception
{
DatagramSocket dg = new DatagramSocket(8888);
new Thread(new Send(dg,8886)).start();
new Thread(new Receive(dg)).start();
}
}
class MyChat_2
{
public static void main(String[] args) throws Exception
{
DatagramSocket dg = new DatagramSocket(8886);
new Thread(new Send(dg,8888)).start();
new Thread(new Receive(dg)).start();
}
}
|