-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnection.java
More file actions
79 lines (71 loc) · 2.25 KB
/
Connection.java
File metadata and controls
79 lines (71 loc) · 2.25 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
package chat;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
/**
* Connection class for Socket Programmed Chat
*
* @author Robert Scott - 2018
*/
public class Connection {
Socket sock; // socket for the connection
static String username; // username tied to connection
ObjectInputStream inStream;
ObjectOutputStream outStream;
/**
* method which connects socket and socket streams to appropriate address
* and port
*
* @return boolean value on successful connection
*/
public boolean connect() {
try {
sock = new Socket("localhost", 5000); // sample connection
inStream = new ObjectInputStream(sock.getInputStream());
outStream = new ObjectOutputStream(sock.getOutputStream());
new ServerListener().start(); // add server listener
/**
* send username to stream so server can read it
*/
outStream.writeObject(username);
} catch (IOException e) {
System.out.println(" * Error connecting to the server.");
System.out.println(e);
return false; // connection failed
}
return true; // otherwise give it the green light
}
/**
* method which disconnects user connection from server
*/
public void disconnect() {
try {
inStream.close(); // close input socket stream
outStream.close(); // likewise for output
sock.close(); // close socket
} catch (IOException e) {
System.out.println(" * Error disconnecting from server.");
System.out.println(e);
}
}
/**
* listener to gleam information about server
*/
class ServerListener extends Thread {
@Override
public void run() {
/**
* as long as server is alive, prompt for input
*/
while (true) {
try {
System.out.println((String) inStream.readObject());
System.out.print(" > ");
} catch (IOException | ClassNotFoundException e) {
break;
}
}
}
}
}