【问题标题】:Android client and Java server TCP communicationAndroid 客户端和 Java 服务器 TCP 通信
【发布时间】:2012-04-21 20:12:00
【问题描述】:

我正在开发一个 Android 应用程序(客户端)并希望它使用 TCP 通信与我的 Java 服务器连接。

我已经完成了代码——简单的程序,客户端发送一条消息,服务器回显它——如下:

服务器代码:

    import java.net.*;


public class Server {

    public static void main(String[] args) {

        int nreq = 1;
        try
        {
            ServerSocket sock = new ServerSocket (8080);
            for (;;)
            {
                Socket newsock = sock.accept();
                System.out.println("Creating thread ...");
                Thread t = new ThreadHandler(newsock,nreq);
                t.start();
            }
        }
        catch (Exception e)
        {
            System.out.println("IO error " + e);
        }
        System.out.println("End!");
    }
}

服务器同一个项目文件中的一个Thread Handler代码:

    import java.io.*;
import java.net.*;

class ThreadHandler extends Thread {
    Socket newsock;
    int n;

    ThreadHandler(Socket s, int v) {
        newsock = s;
        n = v;
    }


    public void run() {
        try {

            PrintWriter outp = new PrintWriter(newsock.getOutputStream(), true);
            BufferedReader inp = new BufferedReader(new InputStreamReader(
                    newsock.getInputStream()));

            outp.println("Hello :: enter QUIT to exit \n");
            boolean more_data = true;
            String line;

            while (more_data) {
                line = inp.readLine();
                System.out.println("Message '" + line + "' echoed back to client.");
                if (line == null) {
                    System.out.println("line = null");
                    more_data = false;
                } else {
                    outp.println("From server: " + line + ". \n");
                    if (line.trim().equals("QUIT"))
                        more_data = false;
                }
            }
            newsock.close();
            System.out.println("Disconnected from client number: " + n);
        } catch (Exception e) {
            System.out.println("IO error " + e);
        }

    }
}

这是客户端(Android):

package com.android.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Client extends Activity {
    /** Called when the activity is first created. */
    Scanner scanner = new Scanner(System.in);

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

        final EditText msg = (EditText) findViewById(R.id.etMsg);
        Button send = (Button) findViewById(R.id.bSend);
        final TextView convo = (TextView) findViewById(R.id.tvConvo);
        final TextView status = (TextView) findViewById(R.id.tvStatus);

        try {
            send.setOnClickListener(new View.OnClickListener() {

                Socket s = new Socket("localhost", 8080);
                String message = msg.getText().toString();

                @Override
                public void onClick(View v) {
                    status.setText("...");
                    PrintWriter outp = null;
                    BufferedReader inp = null;
                    status.setText("Established connection..");
                    String serverMsg = null;

                    try {
                        outp = new PrintWriter(s.getOutputStream(), true);
                        inp = new BufferedReader(new InputStreamReader(s.getInputStream()));
                        serverMsg = inp.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    convo.append(serverMsg + "\n");

                    if (message != null) {
                        if (msg.getText().toString().trim() == "QUIT") {
                            try {
                                s.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            status.setText("Disconnected from server.");

                        } else {
                                try {

                                    convo.append(message + "\n");
                                    outp.println(message); 
                                    serverMsg = inp.readLine();
                                    convo.append(serverMsg + "\n");
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                        }

                    }
                    else
                        status.setText("Problem in connection..!");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这是 XML 文件:

<?xml version="1.0" encoding="utf-8" ?> 
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
  <TextView android:id="@+id/tvText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Your message here:" /> 
- <EditText android:id="@+id/etMsg" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10">
  <requestFocus /> 
  </EditText>
  <TextView android:id="@+id/tvStatus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Status..." android:textAppearance="?android:attr/textAppearanceSmall" /> 
  <Button android:id="@+id/bSend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" /> 
  <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Conversation:" android:textAppearance="?android:attr/textAppearanceLarge" /> 
  <TextView android:id="@+id/tvConvo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> 
  </LinearLayout>

我尝试运行它,但没有任何反应。当我单击按钮时,TextView 不会查看来自服务器的“Hello”消息。

【问题讨论】:

  • 您的 manifest.xml 中是否设置了 &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
  • 是的,有 INTERNET 权限

标签: android tcp client communication


【解决方案1】:

您将 Android 客户端连接到 localhost

Socket s = new Socket("localhost", 8080);

这仅在您的服务器在 Android 设备上运行时才有效。但我认为它正在您的 PC 上运行。因此,当您在 Android 模拟器上运行您的应用程序时,您可以连接到 10.0.2.2 以联系主机。在真实设备上,您必须找出可以通过 Android 设备访问的服务器 IP 地址,例如通过 Wi-Fi。

【讨论】:

  • 您好 Diewie,我正在尝试通过 Internet 将客户端 (Android) 连接到我的 PC,我该怎么做? - 我尝试通过 WiFi 连接它,它通过将 10.2.0.0 替换为我的笔记本电脑的 IP 地址来工作。
  • 只有当您的 PC 可以直接从 Internet 访问或存在相应的端口转发规则时,这才有效。您当前的设置如何?
【解决方案2】:

如果您的服务器在 Windows 上,请在“开始”菜单搜索框中键入 cmd,然后在命令提示符处键入 ipconfig。您将看到类似IVP4 Address----- 192.168.0.101 的内容。您需要在客户端上使用此地址和端口号。

【讨论】:

    猜你喜欢
    • 2013-12-14
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多