本帖最后由 来男. 于 2014-5-4 19:13 编辑
import java.io.*;
import java.net.*;
//客户端
class Send implements Runnable
{
//创建UDP流对象
private DatagramSocket ds;
public Send(DatagramSocket ds)
{
this.ds=ds;
}
//复写run方法
public void run()
{
try
{
//标准键盘读取语句
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
String line=null;
while((line=bufr.readLine())!=null)
{
//over时客户端退出
if("over".equals(line))
break;
//将读取的信息以字节数组形式保存
byte[] buf=line.getBytes();
//定义数据包
DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("196.168.0.2"),10007);
//将包传出
ds.send(dp);
}
}
catch (Exception e)
{
throw new RuntimeException("发送端失败!");
}
//关流
ds.close();
}
}
//服务端
class Rece implements Runnable
{
private DatagramSocket ds;
public Rece(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try
{
while (true)
{
//定义存储容器
byte[] buf=new byte[1024];
//定义数据包
DatagramPacket dp=new DatagramPacket(buf,buf.length);
//接包
ds.receive(dp);
//得到客户端id
String id=dp.getAddress().getHostAddress();
//得到包中信息
String data=new String(dp.getData(),0,dp.getLength());
System.out.println(id+":"+data);
}
}
catch (Exception e)
{
throw new RuntimeException("接受端失败!");
}
}
}
class ChatDemo
{
public static void main(String[] args) throws Exception
{
DatagramSocket sendSocket=new DatagramSocket();
DatagramSocket receSocket=new DatagramSocket(10007);
//开启线程
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();
}
}
我敲完运行没报错(之前有几个母拼错..改了),也没出现阻塞情况,能发不能接且无法结束,over也不行,请问这是怎么回事??
|