1 package be
.nikiroo
.utils
.serial
;
3 import java
.io
.BufferedReader
;
4 import java
.io
.IOException
;
5 import java
.io
.InputStreamReader
;
6 import java
.io
.OutputStreamWriter
;
7 import java
.net
.Socket
;
9 import be
.nikiroo
.utils
.Version
;
11 abstract class ConnectAction
{
13 private boolean server
;
14 private Version version
;
16 private Object lock
= new Object();
17 private BufferedReader in
;
18 private OutputStreamWriter out
;
19 private boolean contentToSend
;
21 // serverVersion = null on server (or bad clients)
22 abstract public void action(Version serverVersion
) throws Exception
;
24 // server = version NULL
25 protected ConnectAction(Socket s
, boolean server
, Version version
) {
29 if (version
== null) {
30 this.version
= new Version();
32 this.version
= version
;
36 public void connectAsync() {
37 new Thread(new Runnable() {
44 public void connect() {
46 in
= new BufferedReader(new InputStreamReader(s
.getInputStream(),
49 out
= new OutputStreamWriter(s
.getOutputStream(), "UTF-8");
54 String v
= sendString("VERSION " + version
.toString());
55 if (v
!= null && v
.startsWith("VERSION ")) {
56 v
= v
.substring("VERSION ".length());
59 action(new Version(v
));
67 } catch (Exception e
) {
72 } catch (Exception e
) {
78 // (also, server never get anything)
79 public Object
send(Object data
) throws IOException
, NoSuchFieldException
,
80 NoSuchMethodException
, ClassNotFoundException
{
82 String rep
= sendString(new Exporter().append(data
).toString(true));
83 return new Importer().read(rep
).getValue();
87 public Object
flush() throws NoSuchFieldException
, NoSuchMethodException
,
88 ClassNotFoundException
, IOException
, java
.lang
.NullPointerException
{
89 String str
= flushString();
91 throw new NullPointerException("No more data from client");
94 return new Importer().read(str
).getValue();
97 protected void onClientVersionReceived(Version clientVersion
) {
101 protected void onError(Exception e
) {
105 // \n included in line, but not in rep (also, server never get anything)
106 private String
sendString(String line
) throws IOException
{
107 synchronized (lock
) {
115 contentToSend
= true;
116 return flushString();
121 // server can receive something even without pending content
122 private String
flushString() throws IOException
{
123 synchronized (lock
) {
124 if (server
|| contentToSend
) {
127 contentToSend
= false;
130 String line
= in
.readLine();
131 if (server
&& line
!= null && line
.startsWith("VERSION ")) {
132 // "VERSION client-version" (VERSION 1.0.0)
133 Version clientVersion
= new Version(
134 line
.substring("VERSION ".length()));
135 onClientVersionReceived(clientVersion
);
136 sendString("VERSION " + version
.toString());
138 line
= in
.readLine();