-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathObjectClient.java
More file actions
executable file
·116 lines (86 loc) · 2.33 KB
/
ObjectClient.java
File metadata and controls
executable file
·116 lines (86 loc) · 2.33 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package threads;
import java.io.*;
import java.net.*;
public class ObjectClient implements CommandLineListener {
ObjectOutputStream objOutputStream;
InetSocketAddress address;
String DEFAULT_HOST = "localhost";
int DEFAULT_PORT = 5000;
boolean isConnected = false;
class IncomingReader implements Runnable {
ObjectInputStream objInputStream;
public IncomingReader(ObjectInputStream ois) {
objInputStream = ois;
}
public void run() {
try {
boolean running = true;
while (running) {
Object obj = objInputStream.readObject();
receive(obj);
}
} catch (EOFException e) {
System.out.println("Lost connection to " + address);
} catch (SocketException e) {
} catch (IOException e) {
} catch (ClassNotFoundException e) {
}
}
}
public void go(){
go(DEFAULT_HOST, DEFAULT_PORT);
}
public void go(String host, int port) {
address = new InetSocketAddress(host, port);
try {
Socket sock = new Socket(host, port);
objOutputStream = new ObjectOutputStream(sock.getOutputStream());
ObjectInputStream objInputStream = new ObjectInputStream(sock
.getInputStream());
System.out.println("Connected to " + address + " from port "
+ sock.getLocalPort());
isConnected = true;
Thread readerThread = new Thread(new IncomingReader(objInputStream));
readerThread.start();
} catch (UnknownHostException e) {
isConnected = false;
} catch (IOException e) {
System.out.println("Could not connect to " + address);
isConnected = false;
}
}
public void userIn(String inString) {
if(inString.equalsIgnoreCase(".close"))
System.exit(0);
send(inString);
}
public boolean send(Object obj) {
try {
objOutputStream.writeObject(obj);
objOutputStream.flush();
return true;
} catch (IOException e) {
System.out.println("Could not send object");
} catch (NullPointerException e) {
System.out.println("Could not send object");
}
return false;
}
public void receive(Object obj) {
System.out.println(obj);
}
public boolean isConnected(){
return isConnected;
}
public static void main(String[] args) {
ObjectClient client = new ObjectClient();
new UserIn(client);
if (args.length < 2) {
client.go();
}
try {
client.go(args[0], Integer.parseInt(args[1]));
} catch (NumberFormatException e) {
}
}
}