简单的TCP服务器 - 客户端使用两个Android模拟器

时间:2012-02-14 08:24:46

标签: android tcp client

有人可以建议我一个简单的演示应用程序,其代码用于了解使用Android模拟器设置TCP服务器 - 客户端配置吗?我对Java套接字编程了解不多,但我对C socket编程非常了解。  非常感谢

2 个答案:

答案 0 :(得分:1)

有很多信息如何创建简单的服务器 - 客户端连接。例如,this文章。在this帖子中,您可以找到演示应用的链接。

答案 1 :(得分:0)

This blog可以帮助您

基础算法: 逐步形式算法的基本描述:

  1. 为服务器MyServer创建两个项目,为客户端创建另一个项目 ServerClient。

  2. 将以下代码段放在res文件夹中 MyServer项目

  3. res / layout / main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:orientation="vertical"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent">
    <TextView 
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="@string/hello"
    />
      <TextView android:text="TextView" android:id="@+id/TextView01"
                  android:layout_width="wrap_content" android:layout_height="wrap_content">
      </TextView>
      </LinearLayout>
    

    3。)将以下代码片段放在ServerClient项目res / layout / main.xml的res文件夹中:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:id="@+id/myTextView"
     />
     <EditText android:text="EditText" android:layout_width="fill_parent" 
      android:id="@+id/EditText01" android:layout_height="wrap_content">
     </EditText>
     <Button android:text="Button" android:id="@+id/myButton"  
      android:layout_width="wrap_content" android:layout_height="wrap_content">
     </Button>
     </LinearLayout>
    

    4。)在两个项目的AndroidManifest.xml中添加以下权限:

     <uses-permission android:name="android.permission.INTERNET"> </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> </uses-permission>
    

    5.。)重定向端口: i)运行 - &gt; cmd - &gt; telnet localhost 5554 ii)redir add tcp:5000:6000 6.)运行这两个应用程序。

    MyServer类如下所示:      包com.app.MyServer;

    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.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.widget.TextView;
    
     public class MyServer extends Activity {
       ServerSocket ss = null;
       String mClientMsg = "";
       Thread myCommsThread = null;
       protected static final int MSG_ID = 0x1337;
       public static final int SERVERPORT = 6000;
    
       @Override
      public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       TextView tv = (TextView) findViewById(R.id.TextView01);
       tv.setText("Nothing from client yet");
       this.myCommsThread = new Thread(new CommsThread());
       this.myCommsThread.start();
       }
    
       @Override
       protected void onStop() {
       super.onStop();
       try {
            // make sure you close the socket upon exiting
           ss.close();
        } catch (IOException e) {
           e.printStackTrace();
        }
       }
    
       Handler myUpdateHandler = new Handler() {
        public void handleMessage(Message msg) {
           switch (msg.what) {
           case MSG_ID:
                TextView tv = (TextView) findViewById(R.id.TextView01);
                tv.setText(mClientMsg);
                break;
            default:
                break;
            }
            super.handleMessage(msg);
        }
      };
       class CommsThread implements Runnable {
        public void run() {
           Socket s = null;
            try {
            ss = new ServerSocket(SERVERPORT );
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!Thread.currentThread().isInterrupted()) {
            Message m = new Message();
            m.what = MSG_ID;
            try {
                if (s == null)
                    s = ss.accept();
                BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                String st = null;
                st = input.readLine();
                mClientMsg = st;
                myUpdateHandler.sendMessage(m);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }
    }
    

    ServerClient类如下所示:

    package com.app.ServerClient;
    
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.view.View;
    
    public class SocketClient extends Activity {
       private Button bt;
       private TextView tv;
       private Socket socket;
       private String serverIpAddress = "10.0.2.2";
       // AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
       // PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
       // PORT 6000
       private static final int REDIRECTED_SERVERPORT = 5000;
       @Override
       public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          bt = (Button) findViewById(R.id.myButton);
          tv = (TextView) findViewById(R.id.myTextView);
          try {
             InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
             socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
          } catch (UnknownHostException e1) {
             e1.printStackTrace();
          } catch (IOException e1) {
             e1.printStackTrace();
              }
          bt.setOnClickListener(new OnClickListener() {
             public void onClick(View v) {
                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);
                   Log.d("Client", "Client sent message");
                } catch (UnknownHostException e) {
                   tv.setText("Error1");
                   e.printStackTrace();
                } catch (IOException e) {
                   tv.setText("Error2");
                   e.printStackTrace();
                } catch (Exception e) {
                   tv.setText("Error3");
                   e.printStackTrace();
                }
             }
          });
       }
    }