0
我已经做了大量的研究,并尝试了各种方法来实现它。我有一个C#服务器,它接受套接字192.168.0.101:18250上的通信。我有下面的代码(下面),它是应用程序的主要活动。我编码的方式是,一切都在onCreate方法,所以套接字应该在应用程序启动后立即连接,但在我的服务器上我没有看到它连接。服务器是完美的,我认为它没有问题。我还尝试了一款来自市场的应用程序,以查看我的手机是否可以连接到服务器,并从该应用程序通过套接字进行通信。这是我在几分钟内扔在一起的代码来测试套接字连接,但不管我尝试套接字只是不会连接。也没有任何例外抛出!Android客户端服务器
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");
}
}
}
你怎么知道套接字不会连接?它应该抛出一个异常,如果它不能解决主机。是否阻止在一条线上? – madmik3 2011-12-29 23:49:08
尝试在'IOException'之后添加一个通用的'catch(Exception e)'块。只是因为'try'块没有遇到可能导致'UnknownHostException'或'IOException'的错误并不意味着没有任何失败。同时检查logcat - 如果有其他类型的异常被抛出,它应该被记录在那里。 – Squonk 2011-12-29 23:53:20
好吧,我得到了一个错误,所有的堆栈跟踪都表示“权限被拒绝”有什么线索发生了什么?我是否需要为清单或某些内容添加某种权限? – 2011-12-30 00:31:26