简体   繁体   English

Android客户端未连接到Java服务器

[英]Android client does not connect to Java server

I'm trying to implement a very simple client/server application in java and android. 我正在尝试在Java和android中实现一个非常简单的客户端/服务器应用程序。 The server seems to run fine when i execute it, and the android client opens on my phone. 当我执行服务器时,服务器似乎运行良好,并且android客户端在手机上打开。 However, when I try to send a message over WiFi connection to the server, it doesn't work. 但是,当我尝试通过WiFi连接向服务器发送消息时,它不起作用。

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: 这是客户端活动的xml布局文件:

<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清单文件的代码:

<?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. 我用System.out.println消息替换了IOException和UnknownHostException printstacktrace,以便我可以确定问题是否来自这些错误中的任何一个。 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. 但是,我之前已经制作了另一个客户端/服务器应用程序,其中客户端和服务器都完全用java作为桌面应用程序进行编码。 In that case, I used localhost (127.0.0.1) as the ip address and tried the application with multiple ports, and it worked. 在这种情况下,我使用本地主机(127.0.0.1)作为IP地址,并尝试了具有多个端口的应用程序,并且该应用程序正常工作。 I also tried that application with my connection's public ip address and it worked. 我还使用连接的公共IP地址尝试了该应用程序,并且该应用程序正常运行。

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. 因此,我开始认为这不是连接端口的问题,而是应用程序的android客户端的问题。 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. 好的,我终于找到了问题,这要归功于greenapps的建议。 Basically, it turns out that firewall was blocking any incoming connections to the java platform on my computer. 基本上,事实证明防火墙阻止了我计算机上与Java平台的任何传入连接。

To fix this: 要解决此问题:

  1. Open up control panel and search for windows firewall 打开控制面板并搜索Windows防火墙
  2. In the Windows Firewall with Advanced Security dialog box on the left, click "Inbound Rules" 在左侧的“具有高级安全性的Windows防火墙”对话框中,单击“入站规则”
  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" 选择属性,然后按“允许连接”或“如果安全则允许连接”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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