簡體   English   中英

Java 實現客戶端服務器 Model(使用 TCP)並從服務器發送 IP 地址並在客戶端上打印出來

[英]Java Implementing a Client Server Model (Using TCP) and sending a IP address from server and Printing it out on Client

服務器代碼:

package exp1;
import java.net.*;
import java.io.*;
public class MyServerSocket{
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
          ServerSocket ss=new ServerSocket(2050); 
          System.out.println("server is waiting..."); 
          Socket s=ss.accept(); 
          
          InetAddress ad= InetAddress.getByName("hostname");
          OutputStream os=s.getOutputStream(); 
          System.out.println("s"+ ad.getHostAddress());
          byte ins=Byte.parseByte(ad.getHostAddress());
          os.write(ins); 
          
          ss.close();
    }
    

}

客戶端代碼:

package exp1;
import java.io.*;
import java.net.*;
public class MyClientSocket {
    public static void main(String[] args) throws Exception{
    Socket s=new Socket(InetAddress.getLocalHost(),2050); 
    InputStream is=s.getInputStream(); 
    System.out.println("Client is ready to receive data"); 
    int d=0; 
    while(d!='#') 
    { 
    d=is.read(); 
    System.out.print((char)d); 
    }        
    }
}

錯誤:

服務器端:

線程“main”中的異常 java.lang.NumberFormatException:對於輸入字符串:“ip”

在 java.base/java.lang.NumberFormatException.forInputString( NumberFormatException.java:67 )

在 java.base/java.lang.Integer.parseInt( Integer.Z93F725A4294C06F21F486FZ )

在 java.base/java.lang.Byte.parseByte( Byte.java:193 )

在 java.base/java.lang.Byte.parseByte( Byte.java:219 )

在 exp1/exp1.MyServerSocket.main([MyServerSocket.java:14]( https://MyServerSocket.Z93F725A07423FE1C889F448B33D21F46:

我正在嘗試在客戶端上顯示本地主機的 ip,但出現錯誤。

getHostAddress返回地址的字符串表示形式。 因此,此方法返回無法解析為字節的192.168.1.100之類的內容。 您可以將字符串作為字節數組傳遞,但這不是最佳解決方案,因為 IPv4 地址只有 4 個字節,但字符串192.168.1.100的長度為 13 個字節!

另外,我不明白行while (d != '#')目的,因為您從不發送任何#符號。

這是對我有用的代碼

class MyServerSocket {
  public static void main(String[] args) throws IOException {
    ServerSocket ss = new ServerSocket(2050);
    System.out.println("server is waiting...");
    Socket s = ss.accept();

    InetAddress ad= InetAddress.getByName("hostname");
    try (OutputStream os = s.getOutputStream()) {
      System.out.println("s"+ ad.getHostAddress());
      os.write(ad.getAddress());
    }
    ss.close();
  }
}

class MyClientSocket {
  public static void main(String[] args) throws Exception{
    Socket s=new Socket(InetAddress.getLocalHost(),2050);
    try (InputStream is = s.getInputStream()) {
      System.out.println("Client is ready to receive data");
      byte[] address = is.readAllBytes();
      InetAddress ad = InetAddress.getByAddress(address);
      System.out.println(ad.getHostAddress());
    }
  }
}

PS關閉您打開的所有資源是避免泄漏的好習慣。 在示例中,我使用了 try-with-resources構造。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM