2015-11-23 57 views
2

所以我試圖在一個項目的進程之間實現套接字通信。但我似乎無法通過回送設備連接到任何端口。我在這裏錯過了什麼嗎?我已經讓它在500個端口上運行,它總是拒絕連接。帶有套接字的Java IPC - 使用環回設備

static final String HOST = "127.0.0.1"; 

public static void main(String[] args) throws IOException { 
    int port = 1000; 
    while (true) { 
     try { 
      socket = new Socket(HOST, PORT); // initialing the socket 
      writer = new OutputStreamWriter(socket.getOutputStream()); 
      reader = new InputStreamReader(socket.getInputStream()); 
      break; 
     } catch (ConnectException ex) { 
      System.out.println("failure on port: " + port); 
      ++port; // increment port to try next 
     } 
    } 

    ... 

}; 

這是整個程序,如果有人想看到聲明和whatnot。

package socket_ipc; 

import java.io.IOException; 
import java.io.OutputStreamWriter; 
import java.io.InputStreamReader; 
import java.net.ConnectException; 
import java.net.Socket; 

public class Socket_IPC { 
    static final int NUMBER_OF_MESSAGES = 100; // number of messages to pass 
    static int[] PRODUCED_MSSG = new int[NUMBER_OF_MESSAGES]; // for comparing 
    static int[] CONSUMED_MSSG = new int[NUMBER_OF_MESSAGES]; // for comparing 

    static final String HOST = "127.0.0.1"; // IP address of loopback device 
    static final int PORT = 1000;    // arbitrary port number (local) 

    static OutputStreamWriter writer; // write to socket 
    static InputStreamReader reader; // read from socket 
    static Socket socket;    // the socket 

    private static class s_Producer extends Thread { 
     @Override 
     public void run() { 
      for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { 
       try { 
        PRODUCED_MSSG[i] = (int)(Math.random() * 256); // get data 
        writer.write(PRODUCED_MSSG[i]); // write data to the socket 
       } catch (IOException ex) { 
        System.err.println(ex.toString()); 
       } 
      } 
     } 
    } 

    private static class s_Consumer extends Thread { 
     @Override 
     public void run() { 
      for(int i = 0; i < NUMBER_OF_MESSAGES; i++) { 
       try { 
        int data = reader.read(); // obtain data from the socket 
        CONSUMED_MSSG[i] = data; // put retrieved data in array 
       } catch (IOException ex) { 
        System.err.println(ex.toString()); 
       } 
      } 
     } 
    } 

    public static void main(String[] args) throws IOException { 
     int port = PORT; // beginning at 1000 
     while (true) { 
      try { 
       socket = new Socket(HOST, port); // initialing the socket 
       writer = new OutputStreamWriter(socket.getOutputStream()); 
       reader = new InputStreamReader(socket.getInputStream()); 
       break; 
      } catch (ConnectException ex) { 
       System.out.println("failure on port: " + port); 
       ++port; // increment port to try next 
      } 
     } 

     /* insanciating and starting the producer process */ 
     s_Producer p = new s_Producer(); 
     p.start(); 

     /* insanciating and starting the consumer process */ 
     s_Consumer c = new s_Consumer(); 
     c.start(); 

     try { /* joining threads to wait for completion */ 
      p.join(); 
      c.join(); 
     } catch (InterruptedException ex) { 
      System.err.println(ex.toString()); 
     } 

     for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { 
      System.out.println(
       "[" + i + "]: " + PRODUCED_MSSG[i] + " == " + CONSUMED_MSSG[i]); 
      if (PRODUCED_MSSG[i] != CONSUMED_MSSG[i]) { 
       System.out.println("PROCESS SYNCHRONIZATION ERROR!"); 
      System.exit(0); 
      } 
     } 

     System.out.println("PROCESS SYNCHRONIZATION SUCCESS!"); 

    } 

}; 
+1

有沒有什麼東西在您試圖連接的端口上偵聽? – fvu

+0

我建議你嘗試連接到有服務已經運行的端口。如果你打印出實際的錯誤,應該說「連接被拒絕」,告訴你沒有任何事情正在監聽那個端口。 –

+0

所以我不會讓套接字在端口上創建時聽到嗎? – whatfield

回答

1

嗯,我不知道究竟是問題的根源,它很好可能是使用的端口號< 1024同樣的,我終於跨過一座集封裝讀者/作家來了,DataOutputStreamDataInputStream類。通過提供基於對象的特定讀取和寫入操作,這些提供了更簡單的解決方案;如dis.readInt()dos.writeInt(int n)

這裏是完成併成功運行的源代碼:

package socket_ipc; 
import java.net.*; 
import java.io.*; 
/** Socket Inter-Process Communication. 
* Implements the Producer-Consumer Problem, using Sockets for IPC. 
* @author William Hatfield: CEG-4350-01 Fall 2015 
*/ 
public class Socket_IPC { 
    static final int NUMBER_OF_MESSAGES = 100; // number of messages to pass 
    static int[] PRODUCED_MSSG = new int[NUMBER_OF_MESSAGES]; // for comparing 
    static int[] CONSUMED_MSSG = new int[NUMBER_OF_MESSAGES]; // for comparing 
    static final String HOST = "127.0.0.1"; // IP address of loopback device 
    static final int PORT = 1234;   // arbitrary port number (local) 
    static ServerSocket serverSocket;  // the shared server socket 
    private static class Producer extends Thread { 
     @Override 
     public void run() { 
      try { 
       Socket toClient = serverSocket.accept(); 
       DataOutputStream dos = new DataOutputStream(toClient.getOutputStream()); 
       for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { 
       PRODUCED_MSSG[i] = 
         (int)((Math.random() - .5) * Integer.MAX_VALUE); 
       dos.writeInt(PRODUCED_MSSG[i]); 
      } 
      } catch (IOException ex) { 
       System.err.println("Producer Error: " + ex.toString()); 
      } 
     } 
    } 
    private static class Consumer extends Thread { 
     @Override 
     public void run() { 
      try { 
       Socket fromServer = new Socket(HOST, PORT); 
       DataInputStream dis = new DataInputStream(fromServer.getInputStream()); 
       for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { 
       CONSUMED_MSSG[i] = dis.readInt(); 
      } 
      } catch (IOException ex) { 
       System.err.println("Consumer Error: " + ex.toString()); 
      }  
     } 
    } 
    public static void main(String[] args) { 
     try { 
      serverSocket = new ServerSocket(PORT); 
      Producer p = new Producer(); // create the producer thread 
      Consumer c = new Consumer(); // create the consumer thread 
      p.start();      // start the producer thread 
      c.start();      // start the consumer thread 
      p.join();      // wait for producer thread 
      c.join();      // wait for consumer thread 
     } catch (InterruptedException | IOException ex) { /* handle later */ } 
     /* compare produced and consumed data, exit if any match fails */ 
     for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { 
      System.out.print("[" + i + "]: " + PRODUCED_MSSG[i]); 
      System.out.println(" == " + CONSUMED_MSSG[i]); 
      if (PRODUCED_MSSG[i] != CONSUMED_MSSG[i]) { 
       System.out.println("PROCESS SYNC ERROR AT INDEX: " + i); 
       System.exit(0); 
      } 
     } 
     /* inform the user that synchroniozation was succesful, then exit */ 
     System.out.println("SYNC SUCCESFUL!"); 
    } 
} 

如果有您想提供任何改善,我很高興地聽着。特別是對於頑固的Java編碼人員,我敢肯定在這裏有一些違背標準Java實踐的東西!

+0

港口號碼。通常阻止<1024;因爲這些是由系統保留的。這就是爲什麼你面臨困難。 –

+0

這是我想通過嘗試解決這個問題之一... – whatfield

相關問題