Simple TCP Listener-Thread for Android.. mine doesn´t connect

风流意气都作罢 提交于 2019-12-23 02:45:17

问题


On Android I tried to implement a simple TCP Listener Thread (or copied it from anywhere). It should simply wait for a Text and then do something. The Text is sent, this part works, but this listener-Thread doesn´t even create the Socket for listening correctly.

Has anyone an Idea, whats wrong or another simple approach for me? The text is defined b myself and not html. I only found much too complicated http-handlers.

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);
}

}

回答1:


The code you showed is used to create a client socket, not a server socket. see below an example of TCP server socket, taken from 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);
         }
      }
}


来源:https://stackoverflow.com/questions/8298100/simple-tcp-listener-thread-for-android-mine-doesn%c2%b4t-connect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!