Android telnet客户端问题

时间:2013-03-01 10:59:22

标签: java tcp telnet

我是Android OS开发的新手。我尝试为android OS开发我的telnet客户端。 现在,我只尝试连接telnet服务器,并接收登录消息。

但是当我启动套接字以连接telnet服务器时,我收到了奇怪的符号??????!????而不是来自telnet服务器的登录消息。

public class MainActivity extends Activity {
    protected static final int TCP_SERVER_PORT = 23;
    protected String inMsg, str;
    static Editable sentence;
    static String modifedSentence;
    BufferedReader inFromUser;
    Socket clientSocket = null;
    DataOutputStream outToServer=null;
    BufferedReader inFromServer=null;        

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startButton = (Button)findViewById(R.id.startButton);
        final TextView textView = (TextView)findViewById(R.id.textView);

        startButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                new Thread(new Runnable() {                   

                    @Override
                    public void run() {             

       //Create socket
        try {
        clientSocket = new Socket("192.168.1.1",23);
       //Create out stream for ClientSocket
            outToServer = new DataOutputStream(clientSocket.getOutputStream());
       //Create ib stream for ClientSocket          
        inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
       //Receive login message from telnet server
            modifedSentence = inFromServer.readLine();
        } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
                 //Update UI activity with login message
         MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                          textView.setText(modifedSentence);
                    }
                });   
        }
             }).start();
    }   
        });         
    }

   protected void onDestroy()
    {
        try {
            clientSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这些“奇怪”符号??????!????表示您使用了错误的编码。创建InputStreamReader时,您应明确指出此流应使用的编码。我不知道您的telnet服务中使用了哪种编码,但您可以尝试各种编码,例如windows-1252

new InputStreamReader(clientSocket.getInputStream(), Charset.forName("windows-1252"))

答案 1 :(得分:0)

Telnet应用程序需要telnet协议才能连接到telnet服务器。这不是一个简单的TCP连接。我使用apache commonse库为telnet访问提供类。 感谢