2016-10-20 36 views
1

即時嘗試連接來自不同計算機的多個客戶端,並使用UDP將消息發送給對方,但這隻適用於本地!任何人都可以指出爲什麼它不在其他計算機上工作?連接多臺計算機Java UDP

PS:我試圖在其他計算機上運行客戶端,並將我的IP地址作爲主機,但它仍然無法工作。

這是我Client.java

import java.io.*; 
import java.net.*; 

public class Client { 

    public static void main(String args[]) throws Exception { 

     // The default port  
     int clientport = 4000; 
     String host = "localhost"; 

     if (args.length < 1) { 
      System.out.println("Usage: UDPClient " + "Now using host = " + host + ", Port# = " + clientport); 
     } 
     // Get the port number to use from the command line 
     else {  
      //host = args[0]; 
      clientport = Integer.valueOf(args[0]).intValue(); 
      System.out.println("Usage: UDPClient " + "Now using host = " + host + ", Port# = " + clientport); 
     } 

     // Get the IP address of the local machine - we will use this as the address to send the data to 
     InetAddress ia = InetAddress.getByName(host); 

     SenderThread sender = new SenderThread(ia, clientport); 
     sender.start(); 
     ReceiverThread receiver = new ReceiverThread(sender.getSocket()); 
     receiver.start(); 
    } 
} 

    class SenderThread extends Thread { 

    private InetAddress serverIPAddress; 
    private DatagramSocket udpClientSocket; 
    private boolean stopped = false; 
    private int serverport; 

    public SenderThread(InetAddress address, int serverport) throws SocketException { 
     this.serverIPAddress = address; 
     this.serverport = serverport; 
     // Create client DatagramSocket 
     this.udpClientSocket = new DatagramSocket(); 
     this.udpClientSocket.connect(serverIPAddress, serverport); 
    } 
    public void halt() { 
     this.stopped = true; 
    } 
    public DatagramSocket getSocket() { 
     return this.udpClientSocket; 
    } 

    public void run() {  
     try {  
      //send blank message 
      byte[] data = new byte[1024]; 
      data = "".getBytes(); 
      DatagramPacket blankPacket = new DatagramPacket(data,data.length , serverIPAddress, serverport); 
      udpClientSocket.send(blankPacket); 

      // Create input stream 
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
      while (true) 
      { 
       if (stopped) 
        return; 

       // Message to send 
       String clientMessage = inFromUser.readLine(); 

       if (clientMessage.equals(".")) 
        break; 

       // Create byte buffer to hold the message to send 
       byte[] sendData = new byte[1024]; 

       // Put this message into our empty buffer/array of bytes 
       sendData = clientMessage.getBytes(); 

       // Create a DatagramPacket with the data, IP address and port number 
       DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverIPAddress, serverport); 

       // Send the UDP packet to server 
       System.out.println("I just sent: "+clientMessage); 
       udpClientSocket.send(sendPacket); 

       Thread.yield(); 
      } 
     } 
     catch (IOException ex) { 
      System.err.println(ex); 
     } 
    } 
} 

class ReceiverThread extends Thread { 

    private DatagramSocket udpClientSocket; 
    private boolean stopped = false; 

    public ReceiverThread(DatagramSocket ds) throws SocketException { 
     this.udpClientSocket = ds; 
    } 

    public void halt() { 
     this.stopped = true; 
    } 

    public void run() { 

     // Create a byte buffer/array for the receive Datagram packet 
     byte[] receiveData = new byte[1024]; 

     while (true) {    
      if (stopped) 
      return; 

      // Set up a DatagramPacket to receive the data into 
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
      System.out.println("I am in the reader!"); 
      try { 
       // Receive a packet from the server (blocks until the packets are received) 
       udpClientSocket.receive(receivePacket); 
       System.out.println("Am i receiving?"); 
       // Extract the reply from the DatagramPacket  
       String serverReply = new String(receivePacket.getData(), 0, receivePacket.getLength()); 

       // print to the screen 
       System.out.println("UDPClient: Response from Server: \"" + serverReply + "\"\n"); 

       Thread.yield(); 
      } 
      catch (IOException ex) { 
      System.err.println(ex); 
      } 
     } 
    } 
} 

這是我Server.java

import java.net.*; // Imported because the Socket class is needed 
import java.util.HashSet; 

public class Server { 

    private static HashSet<Integer> portSet = new HashSet<Integer>(); 

    public static void main(String args[]) throws Exception { 

     // The default port  
     int serverport = 4000;   

     if (args.length < 1) { 
      System.out.println("Usage: UDPServer " + "Now using Port# = " + serverport); 
     } 
     // Get the port number & host to use from the command line 
     else {    
      serverport = Integer.valueOf(args[0]).intValue(); 
      System.out.println("Usage: UDPServer " + "Now using Port# = " + serverport); 
     } 

     // Open a new datagram socket on the specified port 
     DatagramSocket udpServerSocket = new DatagramSocket(serverport);   

     System.out.println("Server started...\n"); 

     while(true) 
     { 
      // Create byte buffers to hold the messages to send and receive 
      byte[] receiveData = new byte[1024];   

      // Create an empty DatagramPacket packet 
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 

      // Block until there is a packet to receive, then receive it (into our empty packet) 
      udpServerSocket.receive(receivePacket);   

      // Extract the message from the packet and make it into a string, then trim off any end characters 
      String clientMessage = (new String(receivePacket.getData())).trim(); 

      // Print some status messages 
      System.out.println("Client Connected - Socket Address: " + receivePacket.getSocketAddress()); 
      System.out.println("Client message: \"" + clientMessage + "\"");   

      // Get the IP address and the the port number which the received connection came from 
      InetAddress clientIP = receivePacket.getAddress();   

      // Print out status message 
      System.out.println("Client IP Address & Hostname: " + clientIP + ", " + clientIP.getHostName() + "\n"); 

      // Get the port number which the recieved connection came from 
      int clientport = receivePacket.getPort(); 
      System.out.println("Adding "+clientport); 
      portSet.add(clientport); 

      // Response message   
      String returnMessage = clientMessage.toUpperCase();   
      System.out.println(returnMessage); 
      // Create an empty buffer/array of bytes to send back 
      byte[] sendData = new byte[1024]; 

      // Assign the message to the send buffer 
      sendData = returnMessage.getBytes(); 

      for(Integer port : portSet) 
      { 
       System.out.println(port != clientport); 
       if(port != clientport) 
       { 
        // Create a DatagramPacket to send, using the buffer, the clients IP address, and the clients port 
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientIP, port); 
        System.out.println("Sending"); 
        // Send the echoed message   
        udpServerSocket.send(sendPacket);  
       } 
      } 
     } 
    } 
} 
+0

您是否試圖取消註釋這個// host = args [0];'? –

+0

你可以嘗試http://jgroups.org/ – atom

+0

@musib顯然我不能使用任何東西只有這個! thanx人 –

回答

0

它不工作,因爲你連你的UDP套接字爲 'localhost' 的。

+0

我應該怎麼做 –

+0

Err,沒有連接到'localhost'? – EJP

+0

所以如果我想要其他電腦連接到我的電腦,不能使用localhost嗎?請問exaplain –

相關問題