如何从服务器向客户端发送消息(TCP,android应用程序)

时间:2014-06-30 16:20:36

标签: android sockets tcp

我创建了两个与套接字连接的android应用程序。客户端将图像发送到服务器,服务器显示它。当你触摸服务器上的图像时,它会得到它的坐标,现在正在运行。我需要的是服务器将坐标发送到客户端,但我不知道如何将它们发送到客户端并检索它们,我应该打开一个新的套接字吗?我不知道该怎么做。请问有人帮我一把吗?

这是我目前的代码

SERVER

package com.example.serverlate;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.TextView;

public class ServerLate extends Activity {

    private ServerSocket serverSocket;
    String touchedCoordinates;
    Handler updateConversationHandler;
    Thread serverThread = null;
    private ImageView imageView;
    public static final int SERVERPORT = 6000;

    @Override
    public void onCreate(Bundle savedInstanceState) {

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

        imageView=(ImageView) findViewById(R.id.imageViewServer);

        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 DataInputStream input;    
        public CommunicationThread(Socket clientSocket) {

            this.clientSocket = clientSocket;

            try {
                InputStream in = this.clientSocket.getInputStream();
                this.input = new DataInputStream(in);               
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    byte[] data;
                    int len= this.input.readInt();                  
                    data = new byte[len];                   
                    if (len > 0) {
                        this.input.readFully(data,0,data.length);
                    }   
                    updateConversationHandler.post(new updateUIThread(data));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    class updateUIThread implements Runnable {
        private byte[] byteArray;

        public updateUIThread(byte[] array){    
            this.byteArray=array;   
        }

        @Override
        public void run() { 
            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray .length);
            imageView.setImageBitmap(bitmap);
            imageView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                touchedCoordinates="Touch coordinates : " +
                        String.valueOf(event.getX()) + " x " + String.valueOf(event.getY());
                    return true;
            }
        });
        }
    }
}

客户端

package com.example.clientlate;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

public class ClientLate extends Activity {

    private Socket socket;

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

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

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

    public void onClick(View view) {
        try {           
            ImageView imageView=(ImageView) findViewById(R.id.imageView1);
            Bitmap bmp=((BitmapDrawable)imageView.getDrawable()).getBitmap(); 

            ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
            bmp.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); 
            byte[] array = bos.toByteArray();

            OutputStream out = socket.getOutputStream(); 
            DataOutputStream dos = new DataOutputStream(out);
            dos.writeInt(array.length);
            dos.write(array, 0, array.length);

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

        }

    }
}

1 个答案:

答案 0 :(得分:1)

你可以在客户端尝试这样的事情:

public class ClientLate extends Activity {
public void onCreate(Bundle savedInstanceState) {
     ....
    updateConversationHandler = new Handler();
    FPSHandler = new Handler();
    new Thread(new ClientThread()).start();
    ....
}
class ClientThread implements Runnable {

    @Override
    public void run() {
        thread1=Thread.currentThread();
        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            socketTE = new Socket(serverAddr, SERVERPORT);
            CommunicationThread commThread = new CommunicationThread(socketTE);
            new Thread(commThread).start();
        } catch (UnknownHostException e1) {
            Toast.makeText(getApplicationContext(), "Connection failed",
                       Toast.LENGTH_SHORT).show();
            finish();
        } catch (IOException e1) {              
            Toast.makeText(getApplicationContext(), "Connection failed",
                       Toast.LENGTH_SHORT).show();
            finish();
        }
    }

}

class CommunicationThread implements Runnable 
{

    private Socket clientSocket;
    private BufferedReader input;
    public CommunicationThread(Socket clientSocket) 
    {
        thread2=Thread.currentThread();
        this.clientSocket = clientSocket;
        try {
            this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
            } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void run() 
    {
        while (running.get()) 
        {
            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() 
    {       
            ...
    }
}
....
}