开发者

writing DataOutputStream in Android

开发者 https://www.devze.com 2023-02-18 04:04 出处:网络
I am trying to set up a socket client to send just an int for the time being with DataOutputStream to a server. My app works fine when I run it from my PC but I get this error message on Android emula

I am trying to set up a socket client to send just an int for the time being with DataOutputStream to a server. My app works fine when I run it from my PC but I get this error message on Android emulator on Eclipse: "The application SOCKET has stopped unexpectedly please try again". Any tips? If you find any other mistakes why this would not work in general any advice is appreciated.

Code of the app for Android:

import java.io.*;  
import java.net.*;  
import android.app.Activity;  
import android.os.Bundle;  
import android.widget.TextView;

public class SOCKET extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        tv.setText("App1 Test");
        setContentView(tv);
        Client app1Test = new Client();
        app1Test.run();
    }

    public class Client implements Runnable{

        @Override
        public void run() {
            int message = 13;
            Socket App1 = null;

                   try {
                     App1 = new Socket("xxxxx.dyndns-remote.com", ####);
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            DataOutputStream output = null;

            try {
                output = new DataOutputStream(App1.getOutputStream());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            try {
                output.write(message);
                output开发者_开发百科.close(); 
                App1.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
    }
}
}


Set the internet permission in your Manifest

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

to allow your application to open sockets. See http://developer.android.com/reference/android/Manifest.permission.html and http://developer.android.com/resources/samples/SampleSyncAdapter/AndroidManifest.html.


Use an array of bytes to send the data.

byte buf [] = message.getBytes ();
output.write(buf);

Saludos.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号