關(guān)于Java Socket網(wǎng)絡(luò)傳輸?shù)男蛄谢瘷C制
采用Java Socket網(wǎng)絡(luò)傳輸?shù)男蛄谢瘷C制,將對象“壓扁”成二進制字節(jié),將二進制字節(jié)在網(wǎng)絡(luò)中傳輸;
自定義協(xié)議,將對象用字符串描述出來,將字符串用二進制表示,在網(wǎng)絡(luò)中傳輸,在另外一邊用相反的策略解析這個字符串,重新構(gòu)造業(yè)務(wù)對象,這個方法能夠在異構(gòu)平臺中進行傳輸而不變形,但是需要額外的編寫“壓扁”和“充氣”的代碼;
我們這里用第一種方法:
1.package stream.demo;
2.import java.io.ByteArrayInputStream;
3.import java.io.ByteArrayOutputStream;
4.import java.io.File;
5.import java.io.FileInputStream;
6.import java.io.FileOutputStream;
7.import java.io.IOException;
8.import java.io.InputStream;
9.import java.io.ObjectInputStream;
10.import java.io.ObjectOutputStream;
11.import java.io.OutputStream;
12.import java.util.Date;
13.public class Persistence {
14.public static void main(String[] args) {
15.byte[] bs = Persistence.toBytes();
16.//在網(wǎng)絡(luò)中進行傳輸
17.Persistence.getBytes(bs);
18.}
19.public static byte[] toBytes() {
20.Person p = new Person();
21.p.setName("corey");
22.p.setTall(171);
23.p.setBirthday(new Date());
24.p.setAddress(new Address("yiyang", "ziyang"));
25.ByteArrayOutputStream out = new
ByteArrayOutputStream();
26.try {
27.ObjectOutputStream oout = new ObjectOutputStream(out);
28.oout.writeObject(p);
29.} catch (IOException e) {
30.// TODO Auto-generated catch block
31.e.printStackTrace();
32.}
33.return out.toByteArray();
34.}
35.public static void getBytes(byte[] bs) {
36.try {
37.ByteArrayInputStream byteIn = new
ByteArrayInputStream(bs);
38.ObjectInputStream in = new ObjectInputStream(byteIn);
39.Person p = (Person) in.readObject();
40.System.out.println(p.getName());
41.System.out.println(p.getTall());
42.System.out.println(p.getBirthday());
43.System.out.println(p.getAddress().getCity());
44.System.out.print(p.getAddress().getStreet());
45.} catch (Exception e) {
46.// TODO Auto-generated catch block
47.e.printStackTrace();
48.}
49.}
50.}
其中服務(wù)端代碼片段為:
51.in = this.getRequestSocket().getInputStream();
52.out = this.getRequestSocket().getOutputStream();
53.byte[] bs = Persistence.toBytes();
54.System.out.println("發(fā)送數(shù)字長度:"+bs.length);
55.out.write(bs);
56.this.getRequestSocket().close();
57.客戶端代碼片段為:
58.InputStream in = request.getInputStream();
59.byte[] bin = new byte[200];
60.int length = 0;
61.while ((length = in.read(bin)) != -1) {
62.System.out.println("length:" + length);
63.Persistence.getBytes(bin);
64.}
【關(guān)于Java Socket網(wǎng)絡(luò)傳輸?shù)男蛄谢瘷C制】相關(guān)文章:
如何傳輸Java對象10-10
Java Socket應(yīng)答與HTTP服務(wù)器的關(guān)系09-30
TCP/IP網(wǎng)絡(luò)編程中socket的行為10-06
Java反射機制常用API10-07
如何解決Java Socket通信技術(shù)收發(fā)線程互斥09-30
Java語言的特點和實現(xiàn)機制06-02
java調(diào)用linux命令傳輸遠程大文件05-24
傳輸介質(zhì)引起的網(wǎng)絡(luò)故障05-19
PHP socket的配置11-23