2014-07-06 2 views
0

소켓 요청을 보내는 네트워크 클래스를 만들었습니다. JAVA - Sockets :: readline() 아무 것도하지 않음

클래스 :

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

public class Network implements Runnable { 
    private boolean isHost = false; 

    private int hostPort = 19250; 
    private int clientPort = 19251; 
    private String host = "127.0.0.1"; 
    private String name = ""; 

    private ServerSocket ownServer = null; 
    private Socket otherServer = null; 
    private DataOutputStream outToServer = null; 
    private BufferedReader inFromServer = null; 
    private boolean isConnected = false; 

    /** 
    * Konstruktor - 
    */ 
    Network(String name) { 
     this.name = name; 
     this.findHost(); 
     // if no host exists, become host itself 
     if (this.isHost == false) { 
      // host da -> become client 
      System.out.println(this.name + ": host found"); 
      try { 
       ownServer = new ServerSocket(this.clientPort); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } else { 
      // kein host da -> become host 
      System.out.println(this.name + ": no host found"); 

      try { 
       ownServer = new ServerSocket(this.hostPort); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

    } 

    /** 
    * connect() - versucht mit anderem server zu connecten fals dies noch nicht 
    * geschehen ist 
    * 
    * @return true/false 
    */ 
    public boolean connect() { 

     if (this.isConnected == false) { 
      try { 
       if (this.isHost) { 
        otherServer = new Socket(this.host, this.clientPort); 
       } else { 
        otherServer = new Socket(this.host, this.hostPort); 
       } 
      } catch (IOException e) { 
       //System.out.println(this.name + ": connect failed"); 
       this.isConnected = false; 
       return false; 
      } 
     } 

     try { 
      outToServer = new DataOutputStream(otherServer.getOutputStream()); 
      inFromServer = new BufferedReader(new InputStreamReader(
        otherServer.getInputStream())); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     //System.out.println(this.name + ": connect sucess"); 
     this.isConnected = true; 
     return true; 
    } 

    /** 
    * findHost() - schaut ob ein Host existiert 
    * 
    * @return true/false 
    */ 
    private boolean findHost() { 
     Socket hostSocket; 
     try { 
      hostSocket = new Socket(this.host, this.getHostPort()); 
      DataOutputStream outToServer = new DataOutputStream(
        hostSocket.getOutputStream()); 
      BufferedReader inFromServer = new BufferedReader(
        new InputStreamReader(hostSocket.getInputStream())); 
      outToServer.writeBytes("uHost?\n");// Fragen ob Host ist 
     } catch (Exception e) { 
      this.isHost = true; 
      return false; // Keine Connection aufgebaut => kein Host vorhanden 
     } 
     this.isHost = false; 
     return true; // Es gibt schon einen Host 
    } 

    public int getClientPort() { 
     return this.clientPort; 
    } 

    public int getHostPort() { 
     return this.hostPort; 
    } 

    public boolean getIsHost() { 
     return this.isHost; 
    } 

    /** 
    * sendToOther() - schickt daten an anderen Server 
    * 
    * @param data 
    */ 
    public void sendToOther(String data) { 
     this.connect(); 
     try { 
      this.outToServer.writeBytes(data); 
      this.outToServer.writeBytes("\n"); //new Line 
      this.outToServer.flush(); 
      System.out.println(this.name + ": " + data 
        + " :: send to other server"); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      this.outToServer.flush(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void run() { 
     // listen to income 
     String line = ""; 
     try { 
      while (true) { 
       System.out.println(this.name + ":111"); 
       while ((line = inFromServer.readLine())!= null) { 
        System.out.println(this.name + ":222"); 
        System.out.println(this.name + ":recieved: " + line); 
       } 
       System.out.println(this.name + ":333"); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public void readAndDo(String data) { 
     System.out.println(this.name + ": data recieved: " + data); 
    } 

} 

주요 방법 :

public class Application { 

    public static void main(String[] args) { 
     Network t1net=new Network("ss1"); 
     Network t2net=new Network("ss2"); 
     t1net.connect(); 
     t2net.connect(); 


     t1net.sendToOther("some text1"); 
     t2net.sendToOther("sometext2"); 



     Thread t1 = new Thread(t1net); 
     t1.start(); 


     Thread t2 = new Thread(t2net); 
     t2.start(); 
    } 

} 

콘솔 :

ss1: no host found 
ss2: host found 
ss1: some text1 :: send to other server 
ss2: sometext2 :: send to other server 
ss2:111 
ss1:111 

에서 netstat -a :

TCP 127.0.0.1:19250  49on41PCX:54538  HERGESTELLT 
    TCP 127.0.0.1:19250  49on41PCX:54540  HERGESTELLT 
    TCP 127.0.0.1:19251  49on41PCX:54539  HERGESTELLT 
    TCP 127.0.0.1:49156  49on41PCX:0   ABHÖREN 
    TCP 127.0.0.1:54538  49on41PCX:19250  HERGESTELLT 
    TCP 127.0.0.1:54539  49on41PCX:19251  HERGESTELLT 
    TCP 127.0.0.1:54540  49on41PCX:19250  HERGESTELLT 

문제는 readline() 명령의 Network.run() 블록 때문입니다. 데이터는 보내고 버는 일은 결코 없습니다.

도움 주셔서 감사합니다.

+0

() 메소드에서 EchoClient.java 및 EchoServer.java를 참조하십시오. 아니면 그게 무슨 뜻이 아닌가? – pubkey

+0

클라이언트와 서버를 분리하여 시작해야합니다.이 방법은 읽기 쉽지 않습니다. 클라이언트에 문자열을 쓰고 난 후에 그냥 flush가 누락되었다고 생각합니다. –

+0

이 경우 분리는 옵션이 아닙니다. 플러시는 네트워크에서 호출됩니다.문자열을 작성한 직후에 sendToOther(). – pubkey

답변

2

잘못된 방법으로 소켓을 사용했습니다.

SS : ServerSocket의

의 : 소켓

은 먼저 두 개의 스레드에 두 ss을 만들어하여 intial ss에 연결이 s을 만들었습니다. 이러한 방식으로 ss1s2에 속하고 ss2s1에 바인딩됩니다. 그리고 입력 및 출력은 s1s2에서만 구현했습니다. 따라서 s1에서 작성하는 경우 s2으로 전송되지 않습니다. 실제로 연결을 받아들이는 다른 소켓을 ss2에서 만들어야합니다. 그리고 ss1과 동일합니다. 내 포인트를 얻길 바랍니다.

실제로 호스트에 대해 하나의 ss 만 만들어야합니다. 그 다음 :

socketHost = ss.accept();

socketClient = new 소켓 (호스트, 포트);

이제이 두 소켓을 사용하여 I/O 스트림을 사용하여 서로 통신 할 수 있습니다.

두 연결을 ab이라고 말하면 조금 전에 알려 주셨습니다. 한 스레드에서 a을 보내고 받고 두 번째 스레드에서 b의 데이터를 보내고 받았습니다.

간단한 소켓 입출력에 대한 자습서를 살펴보면 이해할 수 있습니다.

편집 : 그것은이 Network.connect에 연결 http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html

관련 문제