无法使用TCP连接通过热点发送邮件。 Android [英] Can't send message over hotspot, using TCP connection. Android

查看:256
本文介绍了无法使用TCP连接通过热点发送邮件。 Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的应用程序,其中我想通过本地WiFi连接使用TCP发送消息。所以我在一个设备上创建热点,并从其他设备连接。

I'm creating an simple app, in which I want to send message over local wifi connection using TCP. So I'm creating hotspot on one device and connect it from other device.

现在,在主机设备上,我正在运行以下服务器应用程序,并在连接设备上运行客户端应用程序。

Now, on hosting device, I'm running following server application and on connecting device I'm running client application.

但是当我在客户端设备上按发送按钮时没有任何反应。我的服务器和客户端代码如下:

But nothing happens when I press send button on client device. My code for both server and client is as following:

服务器代码:

import android.os.Bundle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.os.Handler;
import android.widget.TextView;

public class MainActivity extends Activity {

private ServerSocket serverSocket;

Handler updateConversationHandler;

Thread serverThread = null;

private TextView text;

public static final int SERVERPORT = 6000;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    text = (TextView) findViewById(R.id.text2);

    updateConversationHandler = new Handler();

    this.serverThread = new Thread(new ServerThread());
    this.serverThread.start();

}

@Override
protected void onStop() {
    super.onStop();
    try {
        serverSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

class ServerThread implements Runnable {

    public void run() {
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(SERVERPORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!Thread.currentThread().isInterrupted()) {

            try {

                socket = serverSocket.accept();

                CommunicationThread commThread = new CommunicationThread(socket);
                new Thread(commThread).start();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class CommunicationThread implements Runnable {

    private Socket clientSocket;

    private BufferedReader input;

    public CommunicationThread(Socket clientSocket) {

        this.clientSocket = clientSocket;

        try {

            this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {

        while (!Thread.currentThread().isInterrupted()) {

            try {

                String read = input.readLine();

                updateConversationHandler.post(new updateUIThread(read));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

class updateUIThread implements Runnable {
    private String msg;

    public updateUIThread(String str) {
        this.msg = str;
    }

    @Override
    public void run() {
        text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
    }
}
}

p>

Code for client:

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

private Socket socket;
private String TAG="XXX";

private static final int SERVERPORT = 5000;
private String SERVER_IP ;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new Thread(new ClientThread()).start();

    SERVER_IP = getWifiApIpAddress();

}

public String getWifiApIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            if (intf.getName().contains("wlan")||intf.getName().contains("ap")) {
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                        .hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && (inetAddress.getAddress().length == 4)) {
                        Log.d(TAG, inetAddress.getHostAddress());
                        return inetAddress.getHostAddress();
                    }
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(TAG, ex.toString());
    }
    return null;
}

public void onClick(View view) {
    try {
        EditText et = (EditText) findViewById(R.id.EditText01);
        String str = et.getText().toString();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())),
                true);
        out.println(str);
   //     out.flush();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

class ClientThread implements Runnable {

    @Override
    public void run() {

        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

            socket = new Socket(serverAddr, SERVERPORT);

        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

}
}

我关注了本教程。 正如解释,它是工作正常在Android模拟器。但不能在实际设备上工作。

I'm following this tutorial. As explained there, It is working fine in android emulators. But doesn't work on actual devices.

所以我认为应该在不同的热点上给出不同的IP地址。所以我在客户端代码中写了一个方法来获取服务器热点的IP地址,而不是连接到它。但是,按发送按钮仍然没有任何反应。

So I thought the IP address should be given different on different hotspots. So I've written a method in client code to get server hotspot's IP address and than connect to it. But still nothing happens on pressing send button.

那么,我在这里缺少什么?我的方法是否正确?在端口号是否有错误?

So, What am I missing here? Is my method correct? Is there any mistakes in port numbers?

在本教程中,作者正在做一些名为端口转发的错误。实际设备的端口转发怎么办?

In the tutorial, author is doing something called port forwarding. What about port forwarding for actual devices?

我在互联网上搜索过这里,但找不到任何确切的解决方案或任何教程解释这种类型的应用程序。请帮助我!

I've searched everywhere for this on Internet but can't find any exact solution or any tutorial explaining this type of application. Please help me!

编辑:

当我在真实设备上运行时, $ c> NllPointerException 在客户端代码中,在以下行:

when I run this in real devices, It is giving NllPointerException in clients code, on following line:

 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);


推荐答案

您不需要在设备上转发任何东西,只需确保您的设备在同一网络&使用您在设置中硬编码或定义的端口。

You don't need to forward anything on device, just make sure your device is on the same network & use the port you have hard-coded or defined in the settings.

我们在仿真器中转发端口,因为它在您的主机上运行,我们告诉主机将来自该特定端口的流量转发到模拟器,因为在实际设备中,您不需要这样做,所以您只需要确保您的设备在同一网络上。正在调用正确的端口。

We forward port in emulator because its running on your host machine & we are telling the host to forward traffic coming on that specific port to emulator, since in an actual device you don't need to do that so you just to have to make sure your device is on the same network & correct port is being called.

这篇关于无法使用TCP连接通过热点发送邮件。 Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆