2 caik89757 caik89757 于 2013.08.19 16:32 提问

android socket编程问题

代码:运行在pc端的代码:
public class SimpleServer {

public static void main(String[] args) throws IOException,
        InterruptedException {
    ServerSocket ss = new ServerSocket(30000);
    while (true) {
        System.out.print("before accept");
        Socket s = ss.accept();
        System.out.print("after accept");
        OutputStream os = s.getOutputStream();
        os.write("你好!我是来自服务器的数据!\n".getBytes("utf-8"));
        os.close();
        s.close();
    }
}

}

运行在android设备上的代码:
public class MainActivity extends Activity {

EditText show;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("tag", "in oncreate");
    show = (EditText) findViewById(R.id.msg_tv);

    myThread.start();
}

Thread myThread = new Thread(new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        Log.d("tag", "in myThread");
        try {
            Log.d("tag", "before socket");
            Socket socket = new Socket("192.168.16.35", 30000);
            Log.d("tag", "after socket");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            String line = br.readLine();
            Log.d("tag", "line-->"+line);
            show.setText("来自服务器的数据: " + line);
            br.close();
            socket.close();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
});

}

服务器端代码运行后,客户端代码在android模拟器上运行达到了我想要的结果,但是在真机上运行却没有出现我想要的结果。
不知道这是为什么?

1个回答

songzhiyong1121
songzhiyong1121   2013.12.10 20:35

真机和电脑是一个局域网吗?可能是问题的关键。

caik89757
caik89757 正解~
大约 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!