2015-06-05 75 views
0

嗨,我建立項目與春季啓動和使用套接字編程在客戶端和服務器之間進行通信。我開始我的項目在本地主機端口號爲8080 而我使用此代碼運行我的客戶端程序:如何在服務器端創建應該給出響應的監聽器?

String serverName = "localhost"; 
     int port = 8080; 
     try { 
      System.out.println("Connecting to " + serverName + " on port " 
        + port); 
      Socket client = new Socket(serverName, port); 
      System.out.println("Just connected to " 
        + client.getRemoteSocketAddress()); 
      OutputStream outToServer = client.getOutputStream(); 
      DataOutputStream out = new DataOutputStream(outToServer); 
      System.out.println("Hello from " + client.getLocalSocketAddress()); 
      out.writeUTF("Hello from " + client.getLocalSocketAddress()); 
      InputStream inFromServer = client.getInputStream(); 
      DataInputStream in = new DataInputStream(inFromServer); 
      System.out.println("Server says " + in.readUTF()); 
      client.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

這「只是連接到127.0.0.1:8080」但線之上拋出異常,程序將打印信息「client.close」:

Connecting to localhost on port 8080 
Just connected to localhost/127.0.0.1:8080 
Hello from /127.0.0.1:37281 
java.io.EOFException 
    at java.io.DataInputStream.readFully(DataInputStream.java:197) 
    at java.io.DataInputStream.readUTF(DataInputStream.java:609) 
    at java.io.DataInputStream.readUTF(DataInputStream.java:564) 
    at com.oodles.Demo.App.main(App.java:39) 

我的要求是如何創建服務器端監聽可以從客戶端處理該消息併發送回一些響應

回答

0

我檢查你的code.Connection確定,但客戶沒有按來自發球的迴應當你使用了in.readUTF();

可以使用波紋管代碼:

字符串服務器名= 「localhost」 的; int port = 8080;

try { 
     System.out.println("Connecting to " + serverName + " on port " 
       + port); 
     Socket client = new Socket(serverName, port); 
     System.out.println("Just connected to " 
       + client.getRemoteSocketAddress()); 
     OutputStream outToServer = client.getOutputStream(); 
     DataOutputStream out = new DataOutputStream(outToServer); 
     System.out.println("Hello from " + client.getLocalSocketAddress()); 
     out.writeUTF("Hello from " + client.getLocalSocketAddress()); 
     InputStream inFromServer = client.getInputStream(); 
     DataInputStream in = new DataInputStream(inFromServer); 

     if (in.read() != -1) { 
      System.out.println("Server says " + in.readUTF()); 
     } 

     client.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
0

由於spring引導在只能理解HTTP的tomcat上運行。所以這裏你的客戶端連接到tomcat服務器,它只能理解HTTP。所以如果你想通過HTTP連接到spring-boot應用程序,那麼通過TCP連接發送HTTP請求到spring-boot應用程序。否則,在spring-boot應用程序上實現一個組件,該組件可以接受某個其他端口上的TCP連接,並按照您的協議進行處理。

相關問題