File: SocketListener.java

package info (click to toggle)
imagej 1.46a-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 4,248 kB
  • sloc: java: 89,778; sh: 311; xml: 51; makefile: 6
file content (68 lines) | stat: -rw-r--r-- 2,161 bytes parent folder | download
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
package ij;
import ij.*;
import ij.io.*;
import java.io.*;
import java.net.*;

/** Runs commands sent to the port returned by ImageJ.getPort(). 
<pre>
  Commands:
    open path (opens a file)
    macro path  (runs a macro file)
    run command-name  (runs an ImageJ menu command)
    eval macro  (evaluates a macro)
    user.dir path  (sets the current directory)
</pre>
*/
public class SocketListener implements Runnable {

	public SocketListener() {
		Thread thread = new Thread(this, "SocketListener");
		thread.start(); 
	}

	public void run() {
		ServerSocket serverSocket = null;
		BufferedReader is;
		Socket clientSocket;
		try {
			serverSocket = new ServerSocket(ImageJ.getPort());
			if (IJ.debugMode) IJ.log("SocketListener: new ServerSocket("+ImageJ.getPort()+")");
			while (true) {
				clientSocket = serverSocket.accept();
				InetAddress address = clientSocket.getInetAddress();
				boolean isLocal = address!=null && address.isLoopbackAddress();
				if (IJ.debugMode)  IJ.log("SocketListener: client="+address+"  "+ isLocal);
				try {
					is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
					String cmd = is.readLine();
					if (IJ. debugMode) IJ.log("SocketListener: command=\""+ cmd+"\"");
					if (cmd.startsWith("open "))
						(new Opener()).openAndAddToRecent(cmd.substring(5));
					else if (isLocal && cmd.startsWith("macro ")) {
						String name = cmd.substring(6);
						String name2 = name;
						String arg = null;
						if (name2.endsWith(")")) {
							int index = name2.lastIndexOf("(");
							if (index>0) {
								name = name2.substring(0, index);
								arg = name2.substring(index+1, name2.length()-1);
							}
						}
						IJ.runMacroFile(name, arg);
					} else if (isLocal && cmd.startsWith("run "))
						IJ.run(cmd.substring(4));
					else if (isLocal && cmd.startsWith("eval ")) {
						String rtn = IJ.runMacro(cmd.substring(5));
						if (rtn!=null)
							System.out.print(rtn);
					} else if (cmd.startsWith("user.dir "))
						OpenDialog.setDefaultDirectory(cmd.substring(9));
				} catch (Throwable e) {}
				clientSocket.close();
			}
 		} catch (IOException e) {}
	}

}