简体   繁体   中英

Android client server

I have done lots of research on this and tried every method out there to get it to work. I have a C# server that accepts communication on the socket 192.168.0.101:18250. I have the following code (below) and it is the main Activity of the app. The way i coded it is that everything is in the onCreate method so the socket should connect as soon as the app is started, but on my server i dont see it connecting. The server is flawless and i assume there is no problem with it. I also tried an app from the market to see if my phone could even manage to connect to the server and from that app it did communicate through the socket just fine. This is the code i threw together in minutes to test out the socket connection, but no matter what i try the socket just wont connect. And none of the exceptions are thrown either!

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");
    }
}
}

The problem was not in the code, the problem was in the manifest. I had to add this line to the manifest to grant the application permission to open Network Sockets.

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

Hope it helps someone out! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM