2016-09-02 20 views
-1

私は、クライアントから数を取得し、2を掛けるクライアントソケットとサーバソケットを持つプログラムを作成しました。 コードはクライアント側に数字を入れさせません。 コード:Javaサーバとのクライアントサーバ通信

クライアント:

public class cli { 

    public static void main(String args[]) throws UnknownHostException, IOException{ 
     Scanner in = new Scanner(System.in); 
     int number,temp; 
     Socket s = new Socket("127.0.0.1", 1342); 
     Scanner c1 = new Scanner(s.getInputStream()); 
     System.out.println("Enter any number"); 
     number = in.nextInt(); 
     PrintStream p = new PrintStream(s.getOutputStream()); 
     p.println(number); 
     temp = c1.nextInt(); 
     System.out.println(temp); 
     in.close(); 
     s.close(); 
     c1.close(); 
    } 
} 

はサーバー:

public class ser { 
    public static void main(String args[]) throws IOException{ 

     ServerSocket s1 = new ServerSocket(1342); 
     Socket ss = s1.accept(); 
     Scanner sc = new Scanner(ss.getInputStream()); 
     int number = sc.nextInt(); 

     int temp = number * 2; 

     PrintStream p = new PrintStream(ss.getOutputStream()); 
     p.println(temp); 
     ss.close(); 
     sc.close(); 
     s1.close(); 
    } 
} 
+1

あなたの問題は十分に説明されていないです。あなたがそれを実行するとどうなりますか? 「私を許さない」という意味はどうですか? –

+0

取得するスタックトレースとは何ですか?私は同じコードを試して、それは大丈夫だった! –

答えて

1

あなたはそれがあなたのケースでは、より適切である、それを書くためにあなたのintDataOutputStreamを読むためにDataInputStreamを使用する必要がありますScannerより。また、リソースを適切に閉じるには、try-with-resoursesステートメントの使用を検討する必要があります。

あなたのコードは、バグを避ける最も良い方法は、読みやすく、維持しやすくなります。

サーバー:

public class ser { 
    public static void main(String args[]) throws IOException { 
     try (ServerSocket s1 = new ServerSocket(1342); 
      Socket ss = s1.accept(); 
      DataInputStream sc = new DataInputStream(ss.getInputStream()); 
      DataOutputStream p = new DataOutputStream(ss.getOutputStream()); 
     ) { 
      p.writeInt(sc.readInt() * 2); 
     } 
    } 
} 

クライアント:

public class cli { 
    public static void main(String args[]) throws IOException { 
     try (Scanner in = new Scanner(System.in); 
      Socket s = new Socket("127.0.0.1", 1342); 
      DataInputStream c1 = new DataInputStream(s.getInputStream()); 
      DataOutputStream p = new DataOutputStream(s.getOutputStream()); 
     ){ 
      System.out.println("Enter any number"); 
      int number = in.nextInt(); 

      p.writeInt(number); 
      System.out.println(c1.readInt()); 
     } 
    } 
} 

出力:

Enter any number 
12 
24 
関連する問題