使用TCP套接字将文本从服务发送到服务器

时间:2015-07-01 18:41:31

标签: android sockets

下面是主要活动代码,我从服务通过广播获得文本,我想使用wifi将此文本转发到服务器。

我原以为我可以将此应用注册为客户端并将文本发送到安装了服务器应用的另一部手机。 但我不知道该怎么做。 它应该在不按任何按钮的情况下自动完成。

任何想法???

这段代码是从不同的例子中汇总而来的,如果它看起来非常粗糙,但至少它可以工作,那就很抱歉;)

我分隔了为TCP客户端添加的行:

//用于套接字客户端启动

//用于套接字客户端

谢谢!

代码

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;


public class MainActivity extends Activity {

public  ResponseReceiver receiver;
public  CountDownTimer countDownTimer;

//for socket client start
private Socket socket;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "192.168.0.106";
//for socket client end


final BroadcastReceiver mReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            //Do something if connected
            Toast.makeText(getApplicationContext(), "SINIHAMMAS OLEMAS", Toast.LENGTH_SHORT).show();
            SystemClock.sleep(3000);
            Intent i = getBaseContext().getPackageManager()
                    .getLaunchIntentForPackage( getBaseContext().getPackageName() );
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
            countDownTimer.cancel();
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            Toast.makeText(getApplicationContext(), "SINIHAMMAS LAHTI", Toast.LENGTH_SHORT).show();

            countDownTimer.start();

        }//else if...
    }//onReceive
};//BroadcastReceiver

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

    long startTime = 30000;
    long interval = 1000;
    countDownTimer = new MyCountDownTimer(startTime, interval);

    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(mReceiver, filter1);
    this.registerReceiver(mReceiver, filter2);
    this.registerReceiver(mReceiver, filter3);

    final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

//for socket client start
    new Thread(new ClientThread()).start();
//for socket client end

    registerReceiver(new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
            Log.d("sinihammas", "Audio SCO state: " + state);

            if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {

                unregisterReceiver(this);
            }//if

        }//onRecieve
    }, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED));//registerReciever

    Log.d("sinihammas", "starting bluetooth");
    am.startBluetoothSco();

    SystemClock.sleep(2000);


            Intent msgIntent = new Intent(MainActivity.this, SimpleIntentService.class);
            startService(msgIntent);

            final Button button = (Button) findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    am.setBluetoothScoOn(false);
                    am.stopBluetoothSco();
                    System.exit(0);
                }
            });

            IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
            filter.addCategory(Intent.CATEGORY_DEFAULT);
            receiver = new ResponseReceiver();
            registerReceiver(receiver, filter);


        }//onCreate

        public class ResponseReceiver extends BroadcastReceiver {
            public static final String ACTION_RESP = "alar.alar.com.rahelividinakes2.MESSAGE_PROCESSED";

            @Override
            public void onReceive(Context context, Intent intent) {
                TextView result = (TextView) findViewById(R.id.textView);
                String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);
                result.setText(Html.fromHtml(text + "<br>" + result.getText()));


**I THINK I SHOULD SEND TEXT HERE, BUT I DONT KNOW HOW**


            }//onReceive

        }//BroadcastReceiver

public class MyCountDownTimer extends CountDownTimer {
    MediaPlayer mediaPlayer = MediaPlayer.create(alar.alar.com.rahelividinakes2.MainActivity.this, R.raw.haire);


    public MyCountDownTimer(long startTime, long interval) {
        super(startTime, interval);
    }

    @Override
    public void onFinish() {
        mediaPlayer.start();
        SystemClock.sleep(7000);
        mediaPlayer.release();

    }

    @Override
    public void onTick(long millisUntilFinished) {

    }


}

//for socket client start
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();
        }
    }
}
//for socket client end

    }//Activity

服务器代码 已编辑

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;


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");
    }
}
}

1 个答案:

答案 0 :(得分:1)

首先,SystemClock.sleep()中的MainActivity.onCreate()由于可能ANR而非常糟糕。

您的问题实际上包含2个子问题:

  1. 如何将数据发送到客户端线程?
  2. 将队列成员添加到活动类。我们将在客户端线程中使用它。

        //for socket client start
        private Socket socket;
        private static final int SERVERPORT = 6000;
        private static final String SERVER_IP = "192.168.0.106";
        private ConcurrentLinkedQueue<String> mSendQueue = new ConcurrentLinkedQueue<String>();
        //for socket client end
    

    让ResponseReceiver将数据添加到队列中。

        public class ResponseReceiver extends BroadcastReceiver {
            public static final String ACTION_RESP = "alar.alar.com.rahelividinakes2.MESSAGE_PROCESSED";
    
            @Override
            public void onReceive(Context context, Intent intent) {
                TextView result = (TextView) findViewById(R.id.textView);
                String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);
                result.setText(Html.fromHtml(text + "<br>" + result.getText()));
    
                MainActivity.this.mSendQueue.add(text);
    
            }//onReceive
    
        }//BroadcastReceiver
    
    1. 如何通过套接字发送数据?
    2. 在ClientThread中使用队列

          class ClientThread implements Runnable {
      
              private final ConcurrentLinkedQueue<String> mQueue;
      
              public ClientThread(ConcurrentLinkedQueue<String> queue) {
                  mQueue = queue;
              }
      
          @Override
          public void run() {
      
          try {
              InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
      
              socket = new Socket(serverAddr, SERVERPORT);
      
              OutputStream stream = socket.getOutputStream();
      
              while(true) {
                  String data = mQueue.poll();
                  if(data == null) {
                      //queue is empty, waiting...
                      SystemClock.sleep(100);
                      continue;
                  }
      
                  byte[] bytes = data.getBytes();
                  stream.write(bytes, 0, bytes.length);
                  stream.flush();
              }
      
          } catch (UnknownHostException e1){
              e1.printStackTrace();
          } catch (IOException e1) {
              e1.printStackTrace();
          } finally {
              //free resources
          }
      }
      }
      //for socket client end