Java Socket网络传输如何才能更好的完成自己的任务?下面我们就来看看有关的代码介绍希望大家有所收获在网络中的两台机器中传输对象前提首先是基于同一个平台这是序列化的基础所以这里主要有两种做法
采用Java <> Socket网络传输的序列化机制将对象压扁成二进制字节将二进制字节在网络中传输
自定义协议将对象用字符串描述出来将字符串用二进制表示在网络中传输在另外一边用相反的策略解析这个字符串重新构造业务对象这个方法能够在异构平台中进行传输而不变形但是需要额外的编写压扁和充气的代码
我们这里用第一种方法
package streamdemo;
import javaioByteArrayInputStream;
import javaioByteArrayOutputStream;
import javaioFile;
import javaioFileInputStream;
import javaioFileOutputStream;
import javaioIOException;
import javaioInputStream;
import javaioObjectInputStream;
import javaioObjectOutputStream;
import javaioOutputStream;
import javautilDate;
public class Persistence {
public static void main(String[] args) {
byte[] bs = PersistencetoBytes();
//在网络中进行传输
PersistencegetBytes(bs);
}
public static byte[] toBytes() {
Person p = new Person();
psetName(corey);
psetTall();
psetBirthday(new Date());
psetAddress(new Address(yiyang ziyang));
ByteArrayOutputStream out = new
ByteArrayOutputStream();
try {
ObjectOutputStream oout = new ObjectOutputStream(out);
ooutwriteObject(p);
} catch (IOException e) {
// TODO Autogenerated catch block
eprintStackTrace();
}
return outtoByteArray();
}
public static void getBytes(byte[] bs) {
try {
ByteArrayInputStream byteIn = new
ByteArrayInputStream(bs);
ObjectInputStream in = new ObjectInputStream(byteIn);
Person p = (Person) inreadObject();
Systemoutprintln(pgetName());
Systemoutprintln(pgetTall());
Systemoutprintln(pgetBirthday());
Systemoutprintln(pgetAddress()getCity());
Systemoutprint(pgetAddress()getStreet());
} catch (Exception e) {
// TODO Autogenerated catch block
eprintStackTrace();
}
}
}
其中服务端代码片段为
in = thisgetRequestSocket()getInputStream();
out = thisgetRequestSocket()getOutputStream();
byte[] bs = PersistencetoBytes();
Systemoutprintln(发送数字长度+bslength);
outwrite(bs);
thisgetRequestSocket()close();
客户端代码片段为
InputStream in = requestgetInputStream();
byte[] bin = new byte[];
int length = ;
while ((length = inread(bin)) != ) {
Systemoutprintln(length: + length);
PersistencegetBytes(bin);
}
以上就是对Java Socket网络传输的详细介绍希望大家有所帮助