0

私の問題を見てくれてありがとう。Socket with java に関する私の問題を説明したいと思います。ソケットを使用して、サーバーがクライアントからの接続を待機するためのものと、クライアントがサーバーに接続するためのものです。2つの問題があります~~

(1)

+++すべてが相互に接続された後、両者は互いにメッセージを交換できます。サーバーとクライアントでそれぞれ独自のメインTHREADを使用して 2 つのアプリケーション コードを既に完成させましたが、それらを相互に通信させることはできません。Windows コマンドを使用して、この 2 つのファイル .class を実行します。最初にサーバーを実行し、次にクライアントを実行します。彼らはお互いに通信できません。これが輻輳の問題なのか知りたいのですが、別のスレッドを立てると、この問題は解決するでしょうか??

(2) この 2 つのアプリケーションを 2 つの Eclipse で実行しようとしています。つまり、各 Eclipse で 1 つのアプリケーションを実行します。なぜこの問題が解決できるのでしょうか??

(3)クライアント用の私のコードは次のとおりです。

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

public class CC {
    public static void main(String args[]){
         Socket   client=null;
         DataInputStream in=null;
         DataOutputStream out=null;
         try{
              client=new Socket("127.0.0.1",2060);
              in=new DataInputStream(client.getInputStream());
              out=new DataOutputStream(client.getOutputStream());
              System.out.println("You are a client,you send message to server");
              Scanner cin=new Scanner(System.in);
              while(true){
                String send=null,receive=null;
                System.out.println("Please input Client message sending to server!");
                send=cin.nextLine();
                out.writeUTF(send);
                receive=in.readUTF();
                System.out.println("Message from Server is:"+receive);
                Thread.sleep(500);  
              } 
         }
    
         catch(Exception e){
            System.out.println("break!"+e);
        
         }
        
   }    

}

ここにサーバー用の私のコードがあります

 import java.util.*;
 import java.io.*;
 import java.net.*;
 public class SS {
  public  static void main(String args[]){
      ServerSocket socketServer=null;
      DataInputStream  in=null;
      DataOutputStream out=null;
      Socket server;
      try{
          socketServer=new ServerSocket(2060);
      }
      catch(Exception e1){
          System.out.println("can't estblish socketServer "+e1);  
      }
      try{
          Scanner cin=new Scanner(System.in);
          System.out.println("you are server ,please send message to client");
          server=socketServer.accept();  
          in=new DataInputStream(server.getInputStream());
          out=new DataOutputStream(server.getOutputStream());
          while(true){
              String send=null,receive=null;
              receive=in.readUTF();
              System.out.println("get message from client is "+receive);
              System.out.println("send message from client");
              send=cin.nextLine();
              out.writeUTF(send);
         }
      }
      catch(Exception e){
         System.out.println("break! "+e);
      }
  }      
}
4

2 に答える 2

0

ありがとう、友人の下でこの問題を解決しました。以前にこのアプリケーションを実行したことがあるために、ポートが占有されていました。その後、このアプリケーションを 2 回目に実行したところ、これら 2 つのアプリケーションはメッセージを転送できませんでした。この 2 つのアプリケーションは完全に正しいです。

于 2013-04-08T15:38:40.733 に答える