java TCP服务器接受来自android客户端的图像和字符串

标签 java android sockets tcp

我想发送字符串消息以及图像。我正在设计 Android 聊天应用程序,该应用程序也允许用户共享图像和聊天(字符串) Java Server 位于后端,负责监听和广播。 我正在阅读几篇文章,但仍然感到困惑。 1)我如何发送数据并且在接收服务器时可以知道它的字符串或图像? 2)我应该有单独的套接字来监听然后分别广播图像和字符串吗 3)我可以有一个对象可以保存字符串以及字节数组中的图像并将其传递到java服务器吗? 请帮忙 我也很困惑是否应该使用 objectoutputstream/dataoutputstream 来实现它。

最佳答案

Keep Seperate Sockets that makes it simpler,or you need syncronisation

1)use objectoutputstream for image thats fastest method of image transfer

2)use dataoutputstream for string

Image Sending code

      File myFile = new File ("d:\\ab.jpg");
      byte [] mybytearray  = new byte [(int)myFile.length()];
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(mybytearray,0,mybytearray.length);
      OutputStream os = sock.getOutputStream();
      System.out.println("Sending...");
      os.write(mybytearray,0,mybytearray.length);
      os.flush();
      os.close();

Image receiving code

    int filesize=6022386; // filesize temporary hardcoded
    long start = System.currentTimeMillis();
    int bytesRead;
    int current = 0;

    File f=new File("d:\\ab.jpg");
    f.createNewFile();
    // receive file
    byte [] mybytearray  = new byte [filesize];
    InputStream is = socket.getInputStream();
    FileOutputStream fos = new FileOutputStream(f);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    bytesRead = is.read(mybytearray,0,mybytearray.length);
    current = bytesRead;
   do {
       bytesRead =
       is.read(mybytearray, current, (mybytearray.length-current));
       if(bytesRead >= 0) current += bytesRead;
    } while(bytesRead > -1);
    count=current;
    Copy=mybytearray.clone();
    bos.write(mybytearray, 0 , current);
    bos.flush();
    long end = System.currentTimeMillis();
    System.out.println(end-start);
    bos.close();
    fos.close();
    Status=true;

关于java TCP服务器接受来自android客户端的图像和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15708220/

相关文章:

java - 动态生成特化类(class)

java - 创建自定义 Jasper 报告布局

Android 使用支持库来支持 SearchView

python - 如何在 Python 中获取套接字的外部 IP?

java - 当新阶段弹出时,我如何禁用初级阶段

java - 使用具有泛型参数的类定义 spring bean

java - 如何清除android中的缓存数据

android - 修改 Android seekbar 小部件以垂直操作

python - 使用多个查询时套接字响应时间变慢

c - 系统命令traceroute c 出错