-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessage.java
More file actions
91 lines (76 loc) · 1.97 KB
/
Message.java
File metadata and controls
91 lines (76 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.io.Serializable;
import java.io.*;
import java.net.Socket;
import java.util.Date;
public class Message implements Serializable{
public static final String SEPERATOR = "#####";
private CodeType code;
private String content;
private int key = -1;
private int port = -1;
private Date time = new Date();
public Message(CodeType code, String content){
this.code = code;
this.content = content;
}
public Message(CodeType code, String content, int port){
this(code, content);
this.port = port;
}
public Message(CodeType code, String content, int port, int key){
this(code, content, port);
this.key = key;
}
public int getPort(){
return port;
}
public int getKey(){
return key;
}
public CodeType getCode(){
return code;
}
public String getContent(){
return content;
}
public byte[] Serialize(){
try{
byte[] bytes = null;
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(b);
out.writeObject(this);
return b.toByteArray();
} catch(IOException e1){
System.out.println(e1);
return null;
}
}
@Override
public int hashCode() {
return key * port * content.hashCode() * time.hashCode();
}
public static Message Deserialize(byte[] b){
try{
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(b);
ObjectInputStream o = new ObjectInputStream(byteInputStream);
return (Message) o.readObject();
}catch(IOException e1){
System.out.println(e1);
return null;
}catch(ClassNotFoundException e2){
System.out.println(e2);
return null;
}
}
@Override
public String toString(){
return code + ": " + content + " - " + port;
}
public static void main(String [] args)
{
Message mes = new Message(CodeType.Success, "Works!");
byte[] b = mes.Serialize();
Message mes2 = Message.Deserialize(b);
System.out.println(mes2.getCode() + ": " + mes.getContent());
}
}