Android客户端服务器

时间:2011-12-29 23:44:05

标签: java android client

我已经对此进行了大量研究并尝试了各种方法以使其发挥作用。我有一个C#服务器,它接受套接字192.168.0.101:18250上的通信。我有以下代码(如下),它是应用程序的主要活动。我编码的方式是所有内容都在onCreate方法中,所以套接字应该在应用程序启动时立即连接,但在我的服务器上我看不到它连接。服务器是完美的,我认为它没有问题。我还尝试了一个来自市场的应用程序,看看我的手机是否能够连接到服务器,从那个应用程序,它确实通过套接字进行通信。这是我在几分钟内一起测试插槽连接的代码,但无论我尝试套接字只是不会连接。也没有抛出异常!

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.*;

public class ClientServerTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {

        InetAddress addr = InetAddress.getByName("192.168.0.101");
        int port = 18250;

        // This constructor will block until the connection succeeds
        Socket socket = new Socket(addr, port);
        socket.getOutputStream();
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        wr.write("Hello World");
        wr.flush();

    } catch (UnknownHostException e) {

        TextView t=(TextView)findViewById(R.id.textView1); 
        t.setText(t.getText() + e.getMessage() + "\r\n");

    } catch (IOException e) {

        TextView t=(TextView)findViewById(R.id.textView1); 
        t.setText(t.getText() + e.getMessage() + "\r\n");
    }
}
}

1 个答案:

答案 0 :(得分:1)

问题不在代码中,问题出现在清单中。我必须将此行添加到清单中以授予应用程序打开网络套接字的权限。

<uses-permission android:name="android.permission.INTERNET" /> 

希望它可以帮助别人! :)