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.datasegment.Command;
|
417
|
10 import alice.datasegment.DataSegment;
|
458
|
11 import alice.datasegment.ReceiveData;
|
345
|
12
|
|
13 public class Connection {
|
|
14
|
419
|
15 public Socket socket;
|
470
|
16 public String name;
|
419
|
17 public LinkedBlockingQueue<Command> sendQueue = new LinkedBlockingQueue<Command>();
|
345
|
18
|
419
|
19 public Connection(Socket socket) {
|
|
20 this.socket = socket;
|
|
21 }
|
417
|
22
|
419
|
23 public Connection() {}
|
345
|
24
|
419
|
25 public void sendCommand(Command cmd) {
|
|
26 try {
|
|
27 sendQueue.put(cmd);
|
|
28 } catch (InterruptedException e) {
|
|
29 e.printStackTrace();
|
|
30 }
|
|
31 }
|
417
|
32
|
419
|
33 public String getInfoString() {
|
|
34 return socket.getInetAddress().getHostName()
|
|
35 + ":" + socket.getPort();
|
|
36 }
|
345
|
37
|
467
|
38 public synchronized void write(Command cmd) {
|
443
|
39 ByteBuffer buffer = cmd.convert();
|
419
|
40 try {
|
|
41 while (buffer.hasRemaining()) {
|
|
42 socket.getChannel().write(buffer);
|
|
43 }
|
|
44 } catch (ClosedChannelException e) {
|
|
45 // when put dataSegment to remote if connection close this dataSemgent put.
|
|
46 putConnectionInfo();
|
417
|
47
|
419
|
48 } catch (IOException e) {
|
|
49 e.printStackTrace();
|
|
50 }
|
|
51 }
|
417
|
52
|
419
|
53 public void close(){
|
|
54 try {
|
|
55 socket.shutdownOutput();
|
|
56 socket.shutdownInput();
|
|
57 socket.close();
|
|
58 } catch (ClosedChannelException e) {
|
470
|
59 return;
|
419
|
60 } catch (IOException e) {
|
470
|
61 return;
|
419
|
62 }
|
417
|
63
|
419
|
64 }
|
|
65
|
|
66 public void putConnectionInfo() {
|
470
|
67 if (name!=null){
|
473
|
68 ConnectionInfo c = new ConnectionInfo(name, socket);
|
470
|
69 ReceiveData rData = new ReceiveData(c, false, false);
|
|
70 DataSegment.getLocal().put("_DISCONNECT", rData, null);
|
|
71 }
|
419
|
72
|
|
73 }
|
345
|
74 }
|