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網絡傳輸的詳細介紹希望大家有所幫助
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25652.html