C#和Android套接字图片发送

时间:2015-04-27 14:29:16

标签: c# android image sockets

我试图为Android做一个新的应用程序。我通过套接字将我的C#应用​​程序与Android应用程序连接,我可以轻松地发送文本。但是,我无法做到的是发送图片。客户端Android应用程序将发送文本,我的桌面应用程序将回答位图图像。我试过Base64编码,但它不适合我。我被卡住了。

C#服务器响应代码 ;

else if(text.ToLower() == "resim")
{
    response = "resim gönderiliyor...";
    byte[] text_ = Encoding.UTF8.GetBytes(response);
    socket.BeginSend(text_, 0, text_.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
    Thread.Sleep(3000);

    byte[] buffer = ToBase64String(ScreenCaptured(), ImageFormat.Bmp);
    socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
}

ToBase64String功能;

public string ToBase64String(Bitmap bmp, ImageFormat imageFormat)
    {
        string base64String = string.Empty;


        MemoryStream memoryStream = new MemoryStream();
        bmp.Save(memoryStream, imageFormat);


        memoryStream.Position = 0;
        byte[] byteBuffer = memoryStream.ToArray();


        memoryStream.Close();


        base64String = Convert.ToBase64String(byteBuffer);
        byteBuffer = null;


        return base64String;
    }

Android客户端;

public void addListener(OnListener listener) {
    this.listener = listener;
}

static Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (flag) {
            bmp = SixtyFourBaseToBitmap(msg.obj.toString());
            if(bmp != null)
            {
                imgView.setImageBitmap(bmp);
            }
            else
            {
                kq += msg.obj.toString() + "\r\n";
                textResponse.setText(kq);
            }
        }

    }
};
public static Bitmap SixtyFourBaseToBitmap(String codedString)
{
    try
    {
        byte[] decodedString = Base64.decode(codedString, Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

        return decodedByte;
    }
    catch (Exception e)
    {
        return null;
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttonConnect = (ImageButton) findViewById(R.id.connect_button);
    settings_button_ = (ImageButton) findViewById(R.id.settings_button);
    textResponse = (TextView) findViewById(R.id.response);
    imgView = (ImageView) findViewById(R.id.response_img);

    preferences= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    editor = preferences.edit();
    ipbilgisi=preferences.getString("ip", "IP Girin");
    portBilgisi= preferences.getString("port", "Port Girin");


    buttonConnect.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            myClientTask = new ClientTask(ipbilgisi, portBilgisi);
            myClientTask.execute();
        }
    });

}
public void goSettings(View v)
{
    Intent i = new Intent(this, Settings.class);
    startActivity(i);
    finish();
}
public class ClientTask extends AsyncTask<String, String, String> implements
        OnListener {

    String dstAddress;
    int dstPort;
    PrintWriter out1;


    ClientTask(String addr, String port) {
        dstAddress = addr;
        dstPort = Integer.parseInt(port);
    }

    @Override
    protected void onProgressUpdate(String... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);

    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        try {

            socket = new Socket(dstAddress, dstPort);
            out1 = new PrintWriter(socket.getOutputStream(), true);
            //out1.print("Hello server!");
            out1.flush();

            BufferedReader in1 = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            do {
                try {
                    if (!in1.ready()) {
                        if (message != null) {
                            MainActivity.handler.obtainMessage(0, 0, -1,
                                    "Server: " + message).sendToTarget();
                            message = "";
                        }
                    }
                    int num = in1.read();
                    message += Character.toString((char) num);
                } catch (Exception classNot) {
                }

            } while (!message.equals("bye"));

            try {
                sendMessage("bye");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                socket.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(String result) {
        try {
            if (socket.isClosed()) {
                flag = false;
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Bağlantı Hatası!", Toast.LENGTH_LONG).show();
        }

        super.onPostExecute(result);
    }

    @Override
    public void listener(String text) {
        // TODO Auto-generated method stub
        sendMessage(text);
    }

    void sendMessage(String msg) {
        try {
            out1.print(msg);
            out1.flush();
            if (!msg.equals("bye"))
                MainActivity.handler.obtainMessage(0, 0, -1, "Me: " + msg)
                        .sendToTarget();
            else
                MainActivity.handler.obtainMessage(0, 0, -1,
                        "Ngắt kết nối!").sendToTarget();
        } catch (Exception ioException) {
            ioException.printStackTrace();
        }
    }

}

public void send(View v) {
    addListener(myClientTask);
    if (listener != null)
        listener.listener(((EditText) findViewById(R.id.editText1))
                .getText().toString());
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    try {
        if (listener != null)
            listener.listener("bye");
        socket.close();
    } catch (Exception e) {
        // TODO: handle exception
    }
    super.onDestroy();
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    try {
        if (listener != null)
            listener.listener("bye");
        socket.close();
    } catch (Exception e) {
        // TODO: handle exception
    }
    super.onStop();
}

public void onClick(View v) {
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    startActivity(intent);
    finish();
}

感谢您的帮助。

最好的问候。

0 个答案:

没有答案