套接字连接android

时间:2011-02-20 13:52:37

标签: android

我正在尝试在android中打开输入和输出流,但我不知道该怎么做。我之前在服务器中使用以下命令在J2ME中打开了套接字连接:

scn = (ServerSocketConnection) Connector.open("socket://:5000");     
String myAddress = scn.getLocalAddress();
si.setText("My address: " + myAddress);
// Wait for a connection.
sc = (SocketConnection) scn.acceptAndOpen();
//Get address of socket connection
String yourAddress = sc.getAddress();
si.setText("Connected to: " + yourAddress);
is = sc.openInputStream();
os = sc.openOutputStream();

现在我想将它放到android中,但它不会让我打开输入和输出流,而且我不得不改变一些我不确定会以同样的方式工作的东西。

scn = (ServerSocket) Connector.open("socket://:5000");    
    String myAddress = scn.getLocalAddress();
        Connection.setText("My address: " + myAddress);
        // Wait for a connection.
        Socket sc = scn.accept();
        //Get address of socket connection
        String yourAddress = sc.getAddress();
        Connection.setText("Connected to: " + yourAddress);
        is = sc.openInputStream();
        os = sc.openOutputStream();

我在android中遇到的错误包括Connector,getLocalAddress,getAddress以及openInput和OutputStreams。

我很感激任何帮助,因为我很难在android中设置它。

由于

编辑:

我已将Android代码更改为:

ServerSocket scn = new ServerSocket(5554);    
    InetAddress myAddress = scn.getInetAddress();
        Connection.setText("My address: " + myAddress);
        // Wait for a connection.
        Socket sc = scn.accept();
        //Get address of socket connection
        InetAddress yourAddress = sc.getInetAddress();
        Connection.setText("Connected to: " + yourAddress);
        is = sc.openInputStream();
        os = sc.openOutputStream();

哪个编译好,但我收到错误:

 is = sc.openInputStream();
        os = sc.openOutputStream();

还有另一种在Android中打开输入和输出流的方法吗?

感谢。

1 个答案:

答案 0 :(得分:3)

您可以尝试此链接上的代码

http://www.helloandroid.com/tutorials/simple-connection-example-part-ii-tcp-communication

让我知道它对你有用。