通过socket传送图片的问题

paperen paperen 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
通过socket传送客户端屏幕图片,但接收端好像始终有数据接收,而接收的数据量会大于送出的图片大小,比较原图片与收到的文件十六进制数据完全不同,本人小白,请各位给我点指导,谢

部分代码如下:

客户端

public class Client
{

public static void main( String[] args )
{

try
{
Socket client = new Socket( "localhost", 5888 );

OutputStream sender = client.getOutputStream();

// 获取到屏幕图片数据
BufferedImage img = Screen.SnapShot();
// 生成文件 这里是可以生成图片的,大小大概为88.7kb
ImageIO.write(img, "png", new File("screen.png"));

// 转为比特后发送
sender.write( Client.getCompressedImage( img ) );

client.close();
}
catch ( IOException e )
{
e.printStackTrace();
}

}

/**
* 图片转换为byte
* @param image
* @return
*/
public static byte[] getCompressedImage( BufferedImage image )
{
byte[] imageData = null;

try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( image, "png", baos );
imageData = baos.toByteArray();
}
catch ( IOException ex )
{
imageData = null;
}

return imageData;
}
}


服务端

public class Server
{

/**
* @param args the command line arguments
*/
public static void main( String[] args )
{
try
{
ServerSocket server = new ServerSocket( 5888 );
Socket client = server.accept();

InputStream inputStream = client.getInputStream();
Scanner sc = new Scanner( inputStream );

String result = "";
int counter = 0;
while( sc.hasNextLine() )
{
result += sc.nextLine();
// 直接限制到400行就停止了,不加的话会一直循环…
if ( counter++ == 400 ) break;
}
byte[] resultToBytes = result.getBytes();

FileOutputStream out = new FileOutputStream( "test.png" );
// 生成的文件大于88.7kb 而且16进制与原图片的不同
out.write( resultToBytes );
out.close();

client.close();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
...全文

相关推荐

评论 22
收藏 已收藏
分享
返回顶部
paperen
Java SE 62,620 成员 307,251 内容