博客
关于我
流中写入文字和图片
阅读量:792 次
发布时间:2019-03-24

本文共 5371 字,大约阅读时间需要 17 分钟。

Java Networking Guide: String and Image Transmission Optimization

String Encoding and Transmission

In this section, we will explore the efficient way to send and receive strings between client and server using Java networking.

Understanding Encoding

Each character in the string is encoded into a 2-byte array. This ensures that both English and Chinese characters are handled correctly. Here’s how the conversion works:

public static byte[] char2byte(char c) {    byte[] bytes = new byte[2];    bytes[0] = (byte)((c & 0xff)); // Low eight bits    bytes[1] = (byte)((c >> 8) & 0xff); // High eight bits    return bytes;}

This method converts each character to a byte array, facilitating easy transmission.

###Efficient String Transmission

For transmission, send the length first and then the byte array:

public class Client {    public static void main(String[] args) {        try {            Socket socket = new Socket("127.0.0.1", 9090);            OutputStream out = socket.getOutputStream();            InputStream input = socket.getInputStream();            String s = "Greetings!";            out.write(s.length());            byte[] bytes = s.getBytes();            out.write(bytes);            out.flush();        } catch (IOException e) {            e.printStackTrace();        }    }}

The server reads the length and reconstructs the string:

public class Server {    public static void main(String[] args) {        try {            ServerSocket serSocket = new ServerSocket(9090);            Socket ser = serSocket.accept();            System.out.println("Connection successful");            InputStream input = ser.getInputStream();            int len = input.read();            byte[] bytes = new byte[len);            input.read(bytes);            String received = new String(bytes);            System.out.println("Received: " + received);        } catch (IOException e) {            e.printStackTrace();        }    }}

Method One: Character-by-Character Conversion

This approach ensures that each character is converted and transmitted independently, avoiding byte array complexity.

Method Two: Utilizing Built-in Methods

Java provides simple methods to handle string conversion, making the implementation straightforward:

public class Client {    public static void main(String[] args) {        try {            Socket socket = new Socket("127.0.0.1", 9090);            OutputStream out = socket.getOutputStream();            InputStream input = socket.getInputStream();            String s = "HelloWorld";            byte[] data = s.getBytes();            out.write(data.length);            out.write(data);            out.flush();        } catch (IOException e) {            e.printStackTrace();        }    }}

The server reconstructs the string using the byte array:

public class Server {    public static void main(String[] args) {        try {            ServerSocket serSocket = new ServerSocket(9090);            Socket ser = serSocket.accept();            System.out.println("Connected");            InputStream input = ser.getInputStream();            byte[] data = new byte[100];            int len = input.read();            input.read(data);            String received = new String(data);            System.out.println("Message received: " + received);        } catch (IOException e) {            e.printStackTrace();        }    }}

This method leverages Java’s built-in functions for simplicity and reliability.

Image Transmission Guide

Efficient image transmission involves structuring the data for effective reading and processing.

Image Data Conversion

Convert images into a compressed format, then serialize each pixel’s byte values for transmission:

public void sendImage(OutputStream out, BufferedImage image) {    try {        int[][] imgData = toArray(image);        int imageWidth = imgData.length;        int imageHeight = imgData[0].length;        out.write(imageWidth);        out.write(imageHeight);        for (int i = 0; i < imageWidth; i++) {            for (int j = 0; j < imageHeight; j++) {                byte color = (byte) imgData[i][j];                out.write(color);            }        }    } catch (IOException e) {        e.printStackTrace();    }}

Reading Image Data

The receiver reconstructs the image using the received data:

public class Server {    public static void main(String[] args) {        try {            ServerSocket serSocket = new ServerSocket(9090);            Socket ser = serSocket.accept();            System.out.println("Image transfer initiated");            InputStream input = ser.getInputStream();            int width = input.read();            int height = input.read();            byte[] imgData = new byte[width * height];            int imgBytes = input.read(imgData);            if (imgBytes != width * height) {                throw new IOException("Incomplete image data");            }            // Reconstruct image from imgData        } catch (IOException e) {            e.printStackTrace();        }    }}

Image Transmission Tip: Use Double Buffering

For smooth rendering, use double buffering to ensure the image is drawn without flicker, enhancing user experience.

Summary

These guides provide a robust framework for efficient string and image transmission in Java networking. Tailor the methods to specific requirements to achieve optimal performance and compatibility.

转载地址:http://jjekk.baihongyu.com/

你可能感兴趣的文章
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>
Mysqldump参数大全(参数来源于mysql5.5.19源码)
查看>>
mysqldump备份时忽略某些表
查看>>
mysqldump实现数据备份及灾难恢复
查看>>
mysqldump数据库备份无法进行操作只能查询 --single-transaction
查看>>
mysqldump的一些用法
查看>>
mysqli
查看>>
MySQLIntegrityConstraintViolationException异常处理
查看>>
mysqlreport分析工具详解
查看>>
MySQLSyntaxErrorException: Unknown error 1146和SQLSyntaxErrorException: Unknown error 1146
查看>>
Mysql_Postgresql中_geometry数据操作_st_astext_GeomFromEWKT函数_在java中转换geometry的16进制数据---PostgreSQL工作笔记007
查看>>
mysql_real_connect 参数注意
查看>>
mysql_secure_installation初始化数据库报Access denied
查看>>
MySQL_西安11月销售昨日未上架的产品_20161212
查看>>
Mysql——深入浅出InnoDB底层原理
查看>>
MySQL“被动”性能优化汇总
查看>>
MySQL、HBase 和 Elasticsearch:特点与区别详解
查看>>
MySQL、Redis高频面试题汇总
查看>>
MYSQL、SQL Server、Oracle数据库排序空值null问题及其解决办法
查看>>