Java Socket网络传输如何才能更好的完成自己的任务?下面我们就来看看有关的代码介绍,希望大家有所收获。在网络中的两台机器中传输对象,前提首先是基于同一个平台,这是序列化的基础,所以这里主要有两种做法:
采用Java Socket网络传输的序列化机制,将对象“压扁”成二进制字节,将二进制字节在网络中传输;
自定义协议,将对象用字符串描述出来,将字符串用二进制表示,在网络中传输,在另外一边用相反的策略解析这个字符串,重新构造业务对象,这个方法能够在异构平台中进行传输而不变形,但是需要额外的编写“压扁”和“充气”的代码;
我们这里用***种方法:
- package stream.demo;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.OutputStream;
- import java.util.Date;
- public class Persistence {
- public static void main(String[] args) {
- byte[] bs = Persistence.toBytes();
- //在网络中进行传输
- Persistence.getBytes(bs);
- }
- public static byte[] toBytes() {
- Person p = new Person();
- p.setName("corey");
- p.setTall(171);
- p.setBirthday(new Date());
- p.setAddress(new Address("yiyang", "ziyang"));
- ByteArrayOutputStream out = new
ByteArrayOutputStream();- try {
- ObjectOutputStream oout = new ObjectOutputStream(out);
- oout.writeObject(p);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return out.toByteArray();
- }
- public static void getBytes(byte[] bs) {
- try {
- ByteArrayInputStream byteIn = new
ByteArrayInputStream(bs);- ObjectInputStream in = new ObjectInputStream(byteIn);
- Person p = (Person) in.readObject();
- System.out.println(p.getName());
- System.out.println(p.getTall());
- System.out.println(p.getBirthday());
- System.out.println(p.getAddress().getCity());
- System.out.print(p.getAddress().getStreet());
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
其中服务端代码片段为:
- in = this.getRequestSocket().getInputStream();
- out = this.getRequestSocket().getOutputStream();
- byte[] bs = Persistence.toBytes();
- System.out.println("发送数字长度:"+bs.length);
- out.write(bs);
- this.getRequestSocket().close();
- 客户端代码片段为:
- InputStream in = request.getInputStream();
- byte[] bin = new byte[200];
- int length = 0;
- while ((length = in.read(bin)) != -1) {
- System.out.println("length:" + length);
- Persistence.getBytes(bin);
- }
以上就是对Java Socket网络传输的详细介绍,希望大家有所帮助。
【编辑推荐】