在这段java代码中如何实现两个不同IP的交流?

墨染白筝
  • 147
import java.io.*;
import java.net.*;

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.105"),10002);
                ds.send(dp);
            }
        }
        catch(Exception e)
        {
            throw new RuntimeException("发送端失败");
        }
    }
}

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)
        {
            throw new RuntimeException("接收端失败");

        }
    }
}

class ChartDemo
{
    public static void main(String[] args)throws Exception
    {
        DatagramSocket sendSocket = new DatagramSocket();
        DatagramSocket receSocket = new DatagramSocket(10002);
        
        new Thread(new Send(sendSocket)).start();
        new Thread(new Rece(receSocket)).start();
    }
}

在上面这段代码里,如果要实现两台电脑的交流,需要在什么样的网络环境下进行呢?
比如我将 DatagramPacket dp =

                new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.105"),10002);这行代码里的ip地址修改一下改成别的电脑的,在什么样的网络环境下可以实现呢?
回复
阅读 2.9k
1 个回答
袁超
  • 1
新手上路,请多包涵

两台电脑在同一个局域网内就没问题

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏