-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththeSocket.java
More file actions
105 lines (94 loc) · 2.42 KB
/
theSocket.java
File metadata and controls
105 lines (94 loc) · 2.42 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Created by linda on 2/2/2017.
*/
public class theSocket {
private String addr;
private int port;
private Socket kkSocket;
private PrintWriter out;
private BufferedReader in;
public theSocket(String addr, int port) {
this.addr = addr;
this.port = port;
}
/*
create a new socket connection
*/
public void createSocket(String whichConnection){
try{
this.kkSocket = new Socket(this.addr, this.port);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
}catch (IOException e){
if(whichConnection.equals("command")){
Utils.errorMessage("FFFC");
System.exit(0);
}
else{
Utils.errorMessage("3A2");
this.closeSocket();
}
}
}
public PrintWriter getout(){
return this.out;
}
public BufferedReader getin(){
return this.in;
}
/*
read a line from the server response
*/
public String readAline(String msg){
String result = null;
try{
result = in.readLine();
}catch(IOException e){
Utils.errorMessage(msg);
closeSocket();
if(msg.equals("FFFD"))
System.exit(0);
}
return result;
}
/*
read a line from the command connection response
*/
public String readTheLine(){
return readAline("FFFD");
}
/*
read a line from the data connection response
*/
public String readDataLine(){
return readAline("3A7");
}
/*
read some byte from the data connection response
*/
public int readChar(byte[] buf) {
int toread = 0;
try{
toread = this.kkSocket.getInputStream().read(buf, 0, buf.length);
}catch(IOException e){
Utils.errorMessage("3A7");
closeSocket();
}
return toread;
}
/*
close the socket
*/
public void closeSocket(){
try{
this.kkSocket.close();
}catch(IOException e){
System.out.println("socket closed");
}
}
}