Android客户端和Java服务器TCP通信

前端之家收集整理的这篇文章主要介绍了Android客户端和Java服务器TCP通信前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个 Android应用程序(客户端),并希望它使用TCP通信与我的Java服务器连接.

我已经完成了代码 – 简单的程序,客户端发送消息,服务器回复它 – 如下所示:

服务器代码

  1. import java.net.*;
  2.  
  3.  
  4. public class Server {
  5.  
  6. public static void main(String[] args) {
  7.  
  8. int nreq = 1;
  9. try
  10. {
  11. ServerSocket sock = new ServerSocket (8080);
  12. for (;;)
  13. {
  14. Socket newsock = sock.accept();
  15. System.out.println("Creating thread ...");
  16. Thread t = new ThreadHandler(newsock,nreq);
  17. t.start();
  18. }
  19. }
  20. catch (Exception e)
  21. {
  22. System.out.println("IO error " + e);
  23. }
  24. System.out.println("End!");
  25. }
  26. }

服务器的同一项目文件中的线程处理程序代码

  1. import java.io.*;
  2. import java.net.*;
  3.  
  4. class ThreadHandler extends Thread {
  5. Socket newsock;
  6. int n;
  7.  
  8. ThreadHandler(Socket s,int v) {
  9. newsock = s;
  10. n = v;
  11. }
  12.  
  13.  
  14. public void run() {
  15. try {
  16.  
  17. PrintWriter outp = new PrintWriter(newsock.getOutputStream(),true);
  18. BufferedReader inp = new BufferedReader(new InputStreamReader(
  19. newsock.getInputStream()));
  20.  
  21. outp.println("Hello :: enter QUIT to exit \n");
  22. boolean more_data = true;
  23. String line;
  24.  
  25. while (more_data) {
  26. line = inp.readLine();
  27. System.out.println("Message '" + line + "' echoed back to client.");
  28. if (line == null) {
  29. System.out.println("line = null");
  30. more_data = false;
  31. } else {
  32. outp.println("From server: " + line + ". \n");
  33. if (line.trim().equals("QUIT"))
  34. more_data = false;
  35. }
  36. }
  37. newsock.close();
  38. System.out.println("Disconnected from client number: " + n);
  39. } catch (Exception e) {
  40. System.out.println("IO error " + e);
  41. }
  42.  
  43. }
  44. }

这是客户端(Android):

  1. package com.android.client;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.PrintWriter;
  7. import java.net.Socket;
  8. import java.util.Scanner;
  9.  
  10. import android.app.Activity;
  11. import android.os.Bundle;
  12. import android.view.View;
  13. import android.widget.Button;
  14. import android.widget.EditText;
  15. import android.widget.TextView;
  16.  
  17. public class Client extends Activity {
  18. /** Called when the activity is first created. */
  19. Scanner scanner = new Scanner(System.in);
  20.  
  21. @Override
  22. public void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.main);
  25.  
  26. final EditText msg = (EditText) findViewById(R.id.etMsg);
  27. Button send = (Button) findViewById(R.id.bSend);
  28. final TextView convo = (TextView) findViewById(R.id.tvConvo);
  29. final TextView status = (TextView) findViewById(R.id.tvStatus);
  30.  
  31. try {
  32. send.setOnClickListener(new View.OnClickListener() {
  33.  
  34. Socket s = new Socket("localhost",8080);
  35. String message = msg.getText().toString();
  36.  
  37. @Override
  38. public void onClick(View v) {
  39. status.setText("...");
  40. PrintWriter outp = null;
  41. BufferedReader inp = null;
  42. status.setText("Established connection..");
  43. String serverMsg = null;
  44.  
  45. try {
  46. outp = new PrintWriter(s.getOutputStream(),true);
  47. inp = new BufferedReader(new InputStreamReader(s.getInputStream()));
  48. serverMsg = inp.readLine();
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. convo.append(serverMsg + "\n");
  53.  
  54. if (message != null) {
  55. if (msg.getText().toString().trim() == "QUIT") {
  56. try {
  57. s.close();
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. status.setText("Disconnected from server.");
  62.  
  63. } else {
  64. try {
  65.  
  66. convo.append(message + "\n");
  67. outp.println(message);
  68. serverMsg = inp.readLine();
  69. convo.append(serverMsg + "\n");
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. }
  74.  
  75. }
  76. else
  77. status.setText("Problem in connection..!");
  78. }
  79. });
  80. } catch (IOException e) {
  81. e.printStackTrace();
  82. }
  83. }
  84. }

这是XML文件

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

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

解决方法

您将Android客户端连接到localhost.
  1. Socket s = new Socket("localhost",8080);

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

猜你在找的Android相关文章