简体   繁体   中英

Android client does not connect to Java server

I'm trying to implement a very simple client/server application in java and android. The server seems to run fine when i execute it, and the android client opens on my phone. However, when I try to send a message over WiFi connection to the server, it doesn't work.

Here is my code for the server:

package com.SentientShadow;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        Thread thread = new Thread(){
            public void run() {
                System.out.println("Server has started and is listening...");
                try{
                    ServerSocket socket = new ServerSocket(6879);
                    while (true){
                        Socket connection = socket.accept();
                        DataInputStream input = new DataInputStream(connection.getInputStream());
                        System.out.println("Received from client: " + input.readUTF());
                        input.close();
                        connection.close();
                    }
                }catch(IOException e){
                    System.out.println("problem accepting connection");
                }
            }   
        };
        thread.start();
    }
}

Here is my code for the client activity:

package com.SentientShadow;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Bundle;

public class Client extends ActionBarActivity implements OnClickListener {
    private EditText etMessage;
    private Button bSend;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);
        etMessage = (EditText)findViewById(R.id.etMessage);
        bSend = (Button)findViewById(R.id.bSend);
        bSend.setOnClickListener(this);
    }

    public void onClick(View view) {
        Thread thread = new Thread(){
            public void run() {
                try {
                    Socket connection = new Socket("127.0.0.1", 6789);
                    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
                    output.writeUTF(etMessage.getText().toString());
                    output.flush();
                    output.close();
                    connection.close();
                } catch (UnknownHostException e) {
                    System.out.println("problem connecting to specified address");
                } catch (IOException e) {
                    System.out.println("problem connecting to port");
                }
            }
        };
        thread.start();
        Toast.makeText(this, "Message has been sent!", Toast.LENGTH_SHORT).show();
    }
}

Here is the xml layout file for the client activity:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.SentientShadow.Client" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter message:" />

    <EditText
        android:id="@+id/etMessage"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="14dp"
        android:ems="10" />

    <Button
        android:id="@+id/bSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:text="Send" />

</RelativeLayout>

Here is my code for the xml manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.SentientShadow"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="Client"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

I replaced the IOException and UnknownHostException printstacktrace with System.out.println messages so that I could determine if the problem is coming from either of those errors. However, nothing was printed to the console.

I also scanned several ports using a port scanner and it seems that my school network has blocked all of them, since they return as closed. However, I've made another client/server application earlier, in which both the client and the server were coded purely in java as a desktop application. In that case, I used localhost (127.0.0.1) as the ip address and tried the application with multiple ports, and it worked. I also tried that application with my connection's public ip address and it worked.

Therefore, I am starting to think that this isn't a problem connecting to a port, but rather a problem with the android client side of the application. But I cannot figure out what is wrong.

By the way, both my phone running the client and my laptop running the server were connected to the same network while I tried to send the message.

Okay, I finally found the problem thanks to the suggestion from greenapps. Basically, it turns out that firewall was blocking any incoming connections to the java platform on my computer.

To fix this:

  1. Open up control panel and search for windows firewall
  2. In the Windows Firewall with Advanced Security dialog box on the left, click "Inbound Rules"
  3. Browse through and see which applications are being blocked from receiving connections
  4. Select the application that you want to allow inbound connections for and right click it
  5. Select properties and press "Allow the connection" or "Allow the connection if secure"

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