本帖最后由 刘菲 于 2012-11-16 08:59 编辑
今天学习了网络编程中聊天的程序,可是却不知道如何才能在dos中让两台机器互相通信,
是两台机器都必须要联网吗,不明白,不会做,麻烦大家帮帮忙!
下面的这个程序只能实现本机的发送和接收。
import java.net.*;
import java.io.*;
class Send implements Runnable
{
private DatagramSocket ds;
public Send(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try
{
BufferedReader bufr=
new BufferedReader(new InputStreamReader(System.in));
String line=null;
while ((line=bufr.readLine())!=null)
{
if("886".equals(line))
break;
byte[] buf=line.getBytes();
DatagramPacket dp=
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10006);
ds.send(dp);
}
ds.close();
}
catch(Exception e)
{}
}
}
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);
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"....."+data);
}
}
catch (Exception e)
{
}
}
}
class ChartDemo
{
public static void main(String[] args)throws Exception
{
DatagramSocket sendso=new DatagramSocket();
DatagramSocket receso=new DatagramSocket(10006);
new Thread(new Send(sendso)).start();
new Thread(new Rece(receso)).start();
}
} |