与插件编程android中的另一个数据一起聊天

时间:2017-03-08 06:55:07

标签: android sockets android-asynctask

我正在开发一个项目,客户端将其活动的屏幕截图发送到服务器,其中位图转换为字符串。对我而言,它运行良好。我想在此项目中添加客户端和服务器之间的聊天。如何我能做到这一点吗?接受任何形式的帮助。

客户代码

   public class Client2 extends AsyncTask<Void, Void, Void> {
     public static String dstAddress;
int dstPort;
String response= new String() ;
String msg_server=new String();
Context context;
   public static   ArrayList<Bitmap>ss=new ArrayList<>();
   public static Socket socket;
Client2(Context ic,String addr, int port,String msg) {
    context=ic;
    dstAddress = addr;
    dstPort = port;
    msg_server=msg;

}

@Override
protected Void doInBackground(Void... arg0) {

    socket = null;
  ObjectOutputStream dataOutputStream = null;
  ObjectInputStream dataInputStream = null;

    try {
        socket = new Socket(dstAddress, dstPort);
        dataOutputStream = new ObjectOutputStream(
                socket.getOutputStream());
        dataInputStream = new ObjectInputStream(socket.getInputStream());

        if(msg_server != null){
            dataOutputStream.writeObject(msg_server);
            dataOutputStream.flush();

        }

        response = (String) dataInputStream.readObject();



    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        response = "UnknownHostException: " + e.toString();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        response = "IOException: " + e.toString();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (socket != null) {
            try {  socket.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (dataOutputStream != null) {
            try {
                dataOutputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (dataInputStream != null) {
            try {
                dataInputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return null;
}

@Override
protected void onPostExecute(Void result) {


    super.onPostExecute(result);
    Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}}

服务器代码

public class Server extends Thread{

ServerSocket serverSocket;
Viewer activity;
static final int SocketServerPORT = 8080;
int count = 0;
int sc=0;
Bitmap bmviewer;
String msgtoclient,msgfromclient;
ArrayList<Bitmap>ser=new ArrayList<>();
public  Server(Activity context,String msg )
 {
activity= (Viewer) context;
msgtoclient=msg;
 }
@Override
public void run() {
    Socket socket = null;
    ObjectInputStream dataInputStream = null;
    ObjectOutputStream dataOutputStream = null;

    try {
       // serverSocket = new ServerSocket(SocketServerPORT);
        serverSocket = new ServerSocket(); // <-- create an unbound socket first
        serverSocket.setReuseAddress(true);
        serverSocket.bind(new InetSocketAddress(SocketServerPORT));// serverSocket.setReuseAddress(true);
        activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Viewer.demo.setText("Port No: "
                        + serverSocket.getLocalPort());
            }
        });

        while (true) {
            socket = serverSocket.accept();
            dataInputStream = new ObjectInputStream(
                    socket.getInputStream());
            dataOutputStream = new ObjectOutputStream(
                    socket.getOutputStream());


            String messageFromClient = new String();
            //If no message sent from client, this code will block the program


            messageFromClient = (String) dataInputStream.readObject();


            count++;

            bmviewer = (stringtobitmap(messageFromClient));

            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    //Viewer.demo.setText(message);
                    sc++;
                    saveimage(bmviewer, sc);
                    // Viewer.images.setImageBitmap(bmviewer);
                    Viewer.imageGallery.addView(getImageView(bmviewer));


                }
            });
      if (msgtoclient.equals("")){
              String reply="received";
                dataOutputStream.writeObject(reply);
                dataOutputStream.flush();}
            else {
            dataOutputStream.writeObject(msgtoclient);
            dataOutputStream.flush();
            }



        }
    }catch(EOFException e){

        e.printStackTrace();
        final String errMsg = e.toString();
        activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
                snackbar.show();
            }
        });
    }   catch(IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        final String errMsg = e.toString();
        activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
                snackbar.show();
            }
        });

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (dataInputStream != null) {
            try {
                dataInputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (dataOutputStream != null) {
            try {
                dataOutputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
private View getImageView(Bitmap image) {
    ImageView imageView = new ImageView(activity);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(0, 0, 10, 0);
    imageView.setLayoutParams(lp);
    imageView.setImageBitmap(image);
    return imageView;
}
private void saveimage(Bitmap bmp,int c) {
    sc=c;
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/screenshare_viewer");
    myDir.mkdirs();
    //Random generator = new Random();
   // int n = 10000;
   // n = generator.nextInt(n);
    String fname = "Image-"+sc +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete ();
    try {
        FileOutputStream out = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

private Bitmap stringtobitmap(String message) {
    try{
        byte [] encodeByte= Base64.decode(message,Base64.DEFAULT);
        Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0,      encodeByte.length);
        return bitmap;
    }
    catch(Exception e){
        e.getMessage();
        return null;
    }
}


}

0 个答案:

没有答案