2011-08-07 3 views
2

내가 여기에 자바 서버를 작성하고있는 코드입니다 :ServerSocket java-server는 입력을 한 번만 읽습니다.

try 
{ 
    ss = new ServerSocket(8080); 
    while (true) 
    { 
     socket = ss.accept(); 
     System.out.println("Acess given"); 

     in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

     //out = new PrintWriter(socket.getOutputStream(),true); 

     line = in.readLine(); 
     System.out.println("you input is :" + in.readLine()); 
    } 
} 

그리고 아이폰 응용 프로그램은 클라이언트입니다과의 코드가있다 : 여기이하는 데 문제가

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    socket = [[LXSocket alloc]init]; 

    if ([socket connect:@"10.211.55.2" port:8080]) { 
     NSLog(@"socket has been created"); 
    } 
    else { 
     NSLog(@"socket couldn't be created created"); 
    } 

    @try { 


    }@catch (NSException * e) { 
     NSLog(@"Unable to send data"); 
    } 

    [super viewDidLoad]; 
} 

-(IBAction)sendData{ 
    [socket sendString:@"A\n"]; 
} 

는 : 먼저 서버가 입력을 한 번만 읽는 것입니다. 두 번째 방법은 두 번 (두 번 uibutton을 클릭) 메서드를 호출 할 때까지 출력하지 않는 데이터를 출력하려고 할 때입니다. 여기에서 무슨 일이 일어나고 있는지 확실하지 않습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

while (server-socket is accepting new connections) 
{ 
    // The server-socket's job is to listen for connection requests 
    // It does this typically in a loop (until you issue server-shutdown) 
    // on accept the server-socket returns a Socket to the newly connected client 
    // 
    socket s = server-socket.accept-connection(); 

    // various options here: 
    // 
    // typically fire off a dedicated thread to servie this client 
    // but also review NIO or (home-grown) connection-map/handler patterns 
    // the general pattern: 
    // create a dedicated thread per connection accepted. 
    // pass Socket (s) to the handler method (a Runnable) and start it off 
    // and that is it. 

    // Here we use the general pattern and create a dedicated 
    // handler thread and pass of the new connections' socket reference 
    // 
    Thread handler-thread = new Thread (handler-routine-as-runnable, s); 
    handler-thread.start(); 
} 
+0

[이전 질문] (http://stackoverflow.com/questions/6975410/serversocket-java-not-reading-inputstream)에 수락 한 답변의 첫 번째 부분을 구현하지 않았습니다. 그렇게. 버퍼링은 차단할 가능성이 매우 높습니다. 어느 시점에서 하천을 닫아야합니다. – Mat

+0

고마워요. –

답변

3

당신은 당신의 while 루프의 새로운 리더 매번 만드는 :

+0

고마워.) –

0

Tushar,

일반적인 패턴이 (거의 자바하지만 의사 코드)입니다. 대신 코드를 while 루프 외부로 이동하고 readLine() 호출을 차단하십시오.

socket = ss.accept(); 
in = new BufferedReader(new InputStreamReader(socket.getInputStream()); 
String line = ""; 
while (true) { 
    line = in.readLine(); 
    System.out.println("you input is :" + line); 
    if ("Bye".equals(line)) 
     break; 
} 

여기에 example 서버 측 프로그램이 있습니다.

1

alphazero 패턴을 기록하기 때문에, 나는 짧은 옷을 벗었 구현 게시 할 예정입니다 :

public class SocketThread extends Thread { 
private Socket communicationSocket = null; 
public SocketThread(Socket clientSocket) { 
communicationSocket = clientSocket; 
try { 
      input = new ObjectInputStream(communicationSocket.getInputStream()); 

     } catch (IOException e) { 
      logger.info("Error getting communication streams to transfer data."); 
      try { 
       communicationSocket.close(); 
      } catch (IOException e1) { 

       e1.printStackTrace(); 
      } 
     } 
} 

public void run() { 
boolean listening=true; 
     DataObject command = null; 
     while (listening) { 
      try { 
       Object currentObject = input.readObject(); 
       if (currentObject != null 
         && currentObject instanceof DataObject) { 
        command = (DataObject) currentObject; 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 

      } catch (ClassNotFoundException e) { 
       e.printStackTrace(); 
      } finally { 
// If we got to this point is because we received a request from 
// the client 
// we can exit the loop 
       listening = false; 
      } 
     } 
} 
} 

참고 :

try { 
      ServerSocket ss = new ServerSocket(portNumber); 
      logger.info("Server successfully started on port " + portNumber); 
      // infinite loop that waits for connections 
      while (true) { 
       SocketThread rst = new SocketThread(ss.accept()); 
       rst.start(); 

      } 
     } catch (IOException e) { 
      logger.info("Error: unable to bind to port " + portNumber); 
      System.exit(-1); 
     } 

SocketThread이 같은입니다 : 이것은 서버입니다

를 : "DataObject"는 소켓에서 얼마나 많은 바이트를 읽지 않고 DataObject 자체를 읽을 수 있기 때문에보다 실용적인 맞춤 클래스 일뿐입니다 DataObject는 Serializable으로 플래그됩니다.

는 도움이되기를 바랍니다.