345
|
1 package alice.daemon;
|
|
2
|
|
3 import java.io.IOException;
|
|
4 import java.net.Socket;
|
|
5 import java.nio.ByteBuffer;
|
417
|
6 import java.nio.channels.ClosedChannelException;
|
345
|
7 import java.util.concurrent.LinkedBlockingQueue;
|
|
8
|
|
9 import alice.codesegment.SingletonMessage;
|
|
10 import alice.datasegment.Command;
|
417
|
11 import alice.datasegment.DataSegment;
|
345
|
12
|
|
13 public class Connection {
|
|
14
|
|
15 public Socket socket;
|
|
16 public LinkedBlockingQueue<Command> sendQueue = new LinkedBlockingQueue<Command>();
|
|
17
|
|
18 public Connection(Socket socket) {
|
|
19 this.socket = socket;
|
|
20 }
|
417
|
21
|
345
|
22 public Connection() {}
|
|
23
|
|
24 public void sendCommand(Command cmd) {
|
|
25 try {
|
|
26 sendQueue.put(cmd);
|
|
27 } catch (InterruptedException e) {
|
|
28 e.printStackTrace();
|
|
29 }
|
|
30 }
|
417
|
31
|
345
|
32 public String getInfoString() {
|
|
33 return socket.getInetAddress().getHostName()
|
417
|
34 + ":" + socket.getPort();
|
345
|
35 }
|
|
36
|
|
37 public synchronized void write(Command cmd) {
|
|
38 CommandMessage cmdMsg = cmd.convert();
|
|
39 ByteBuffer buffer;
|
|
40 try {
|
|
41 buffer = ByteBuffer.wrap(SingletonMessage.getInstance().write(cmdMsg));
|
|
42 while (buffer.hasRemaining()) {
|
|
43 socket.getChannel().write(buffer);
|
|
44 }
|
417
|
45 } catch (ClosedChannelException e) {
|
|
46 // when put dataSegment to remote if connection close this dataSemgent put.
|
|
47 putConnectionInfo();
|
|
48
|
345
|
49 } catch (IOException e) {
|
|
50 e.printStackTrace();
|
|
51 }
|
|
52 }
|
417
|
53
|
345
|
54 public void close(){
|
|
55 try {
|
|
56 socket.shutdownOutput();
|
|
57 socket.shutdownInput();
|
|
58 socket.close();
|
417
|
59 } catch (ClosedChannelException e) {
|
|
60 putConnectionInfo();
|
345
|
61 } catch (IOException e) {
|
|
62 e.printStackTrace();
|
|
63 }
|
417
|
64
|
|
65 }
|
|
66
|
|
67 public void putConnectionInfo() {
|
|
68 ConnectionInfo c = new ConnectionInfo(socket.getInetAddress().toString() ,socket.getPort());
|
|
69 DataSegment.getLocal().put("disconnect", c);
|
345
|
70
|
|
71 }
|
|
72 }
|