大大们,我用java写了两个小程序。是遵从UDP协议的,但是一个发送的(在A电脑上),另个是接收的(B电脑上)。
大婶们看下我代码,看下哪里有问题?
}
class Send implements Runnable
{
private DatagramSocket ds;
Send(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try
{
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
DatagramPacket pack;
String line=null;
while(true)
{
line=buf.readLine();
if("886".equals(line))
{
break;
}
byte [] b=line.getBytes();
pack=new DatagramPacket(b,b.length,InetAddress.getByName("171.116.81.58"),7001);
ds.send(pack);
}
buf.close();
ds.close();
}
catch(Exception e)
{
throw new RuntimeException("发送端异常");
}
}
}
class Receive implements Runnable
{
private DatagramSocket ds;
Receive(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try
{
byte [] buf=new byte[1024];
DatagramPacket pack=new DatagramPacket(buf,buf.length);
while(true)
{
ds.receive(pack);
String ip=pack.getAddress().getHostAddress();
String s=new String(pack.getData(),0,pack.getLength());
System.out.println(ip+" "+s);
}
}
catch(Exception e)
{
throw new RuntimeException("接收端异常");
}
}
}
public class 聊天
{
public static void main(String [] args)throws Exception
{
DatagramSocket ds=new DatagramSocket(2014);
Send s=new Send(ds);
Receive r=new Receive(ds);
new Thread(s).start();
new Thread(r).start();
}
//另个电脑上的代码
import java.io.*;
import java.net.*;
/*
* 建立一个Dos命令行聊天程序
*
* 运行两个同样的程序
* 每个程序有两个线程,一个用于读数据,一个用于发送数据
*/
class Send implements Runnable
{
private DatagramSocket ds;
Send(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try
{
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
DatagramPacket pack;
String line=null;
while(true)
{
line=buf.readLine();
if("886".equals(line))
{
break;
}
byte [] b=line.getBytes();
pack=new DatagramPacket(b,b.length,InetAddress.getByName("192.168.1.101"),2014);
ds.send(pack);
}
buf.close();
ds.close();
}
catch(Exception e)
{
throw new RuntimeException("发送端异常");
}
}
}
class Receive implements Runnable
{
private DatagramSocket ds;
Receive(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try
{
byte [] buf=new byte[1024];
DatagramPacket pack=new DatagramPacket(buf,buf.length);
while(true)
{
ds.receive(pack);
String ip=pack.getAddress().getHostAddress();
String s=new String(pack.getData(),0,pack.getLength());
System.out.println(ip+" "+s);
}
}
catch(Exception e)
{
throw new RuntimeException("接收端异常");
}
}
}
public class 聊天
{
public static void main(String [] args)throws Exception
{
DatagramSocket ds=new DatagramSocket(7001);
Send s=new Send(ds);
Receive r=new Receive(ds);
new Thread(s).start();
new Thread(r).start();
}
}
------解决方案--------------------
先把服务器开启,开启完成以后,再执行客服端代码。 不要一起执行。