2011-11-28 1 views
1

안드로이드에서 간단한 TCP Listener Thread를 구현하려고했는데 (어디서나 복사). 그것은 단순히 텍스트를 기다린 다음 무언가를해야합니다. 텍스트가 전송되었지만이 부분은 작동하지만이 수신기 스레드는 올바르게 듣기 위해 소켓을 만들지 않습니다.안드로이드를위한 Simple TCP Listener-Thread 광산이 연결되지 않음

나에게 아이디어, 잘못된 점 또는 다른 간단한 접근법이있는 사람이 있습니까? 텍스트는 html이 아닌 b 자신으로 정의됩니다. 나는 너무 복잡한 http-handler 만 발견했다.

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

public class Client implements Runnable { 



    public static void main(String args[]) { 

     System.out.print("Listening Thread started\n"); 

     try { 
     Socket skt = new Socket("localhost", 2999); 
     BufferedReader in = new BufferedReader(new 
      InputStreamReader(skt.getInputStream())); 
     System.out.print("Received string: '"); 

     while (!in.ready()) {} 
     System.out.println(in.readLine()); // Read one line and output it 

     System.out.print("'\n"); 


     in.close(); 
     } 
     catch(Exception e) { 
     System.out.print("Whoops! It didn't work!\n"); 
     System.err.println(e); 
     } 
    } 
    public Client() { 

    } 
@Override 
public void run() { 
    // TODO Auto-generated method stub 
    main(null); 
} 

} 
+0

예외가 있습니까? 무슨 예외? – MByD

+0

11-28 15 : 39 : 22.488 : I/System.out (279) : 듣기 스레드가 시작되었습니다. 11-28 15 : 39 : 22.528 : I/System.out (279) : 웁스! 그것은 작동하지 않았다! 11-28 15 : 39 : 22.548 : W/System.err (279) : java.net.ConnectException : localhost/127.0.0.1 : 2999 - 연결이 거부되었습니다 – nico

답변

3

표시된 코드는 서버 소켓이 아닌 클라이언트 소켓을 만드는 데 사용됩니다. 아래의 TCP 서버 소켓 예를 참조하십시오. SystemBash :

class TCPServer 
{ 
    public static void main(String argv[]) throws Exception 
     { 
     String clientSentence; 
     String capitalizedSentence; 
     ServerSocket welcomeSocket = new ServerSocket(6789); 

     while(true) 
     { 
      Socket connectionSocket = welcomeSocket.accept(); 
      BufferedReader inFromClient = 
       new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); 
      DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); 
      clientSentence = inFromClient.readLine(); 
      System.out.println("Received: " + clientSentence); 
      capitalizedSentence = clientSentence.toUpperCase() + '\n'; 
      outToClient.writeBytes(capitalizedSentence); 
     } 
     } 
} 
+0

감사합니다. 내 머리가 막혔습니다. 이것은 분명히 더 많은 논리입니다.) – nico