适用于 Android 的简单 TCP 侦听器线程 .. 我的无法连接 [英] Simple TCP Listener-Thread for Android.. mine doesn´t connect

查看:25
本文介绍了适用于 Android 的简单 TCP 侦听器线程 .. 我的无法连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Android 上,我尝试实现一个简单的 TCP 侦听器线程(或从任何地方复制它).它应该只是等待一个 Text 然后做一些事情.文本被发送,这部分工作,但这个监听器线程甚至没有创建用于正确监听的 Socket.

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.

有没有人有想法,有什么问题或对我来说有其他简单的方法吗?文本是由我自己定义的,而不是 html.我只发现过于复杂的 http 处理程序.

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

}

推荐答案

您展示的代码用于创建客户端套接字,而不是服务器套接字.请参阅下面的 TCP 服务器套接字示例,取自 SystemBash:

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

这篇关于适用于 Android 的简单 TCP 侦听器线程 .. 我的无法连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆