📄 interfacethread.java
字号:
package sjc;
import java.io.*;
import java.net.*;
import javax.net.*;
import javax.net.ssl.*;
public class InterfaceThread extends Thread {
public InterfaceThread(ManagerThread mt) {
mthread = mt;
}
private BufferedReader console = null;
private ManagerThread mthread = null;
private ObjectQueue queue = new ObjectQueue();
public ObjectQueue getQueue() {
return queue;
}
public void run() {
initConsole();
askForConnect();
while (!isInterrupted()) {
proceed(queue.get());
}
}
private void initConsole() {
console = new BufferedReader(new InputStreamReader(System.in));
}
private void askForConnect() {
try {
boolean correct = false;
while (!correct) {
System.out.print("Connect to another host (Y) or listen for connections (N)?");
System.out.flush();
char yn = (console.readLine() + " ").charAt(0); /*the " " is a bugfix in case someone just presses enter */
/* it is faster to chack both uppercase and lowercase than to use toLowerCase() method */
if (yn == 'y' || yn == 'Y') {
mthread.getQueue().put(ManagerThread.YES);
correct = true;
} else if (yn == 'n' || yn == 'N') {
mthread.getQueue().put(ManagerThread.NO);
correct = true;
} else {
System.out.println("Please enter a Y or N");
}
}
} catch (IOException e) {
}
}
private void proceed(Object obj) {
try {
if (obj == ManagerThread.CONNECT) {
boolean correct = false;
InetAddress addr = null;
while (!correct) {
System.out.print("IP Address or Hostname:");
System.out.flush();
String ipaddr = console.readLine();
if (ipaddr == "") {
System.out.println("Please enter an IP Address or a Hostname");
} else {
try {
addr=InetAddress.getByName(ipaddr);
SSLSocket sslsock = (SSLSocket) SSLSocketFactory.getDefault().createSocket(addr, 40000);
sslsock.setEnabledCipherSuites(new String[] {"SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"/* "SSL_DH_anon_WITH_RC4_128_MD5" */});
System.out.println("Connection successful");
mthread.getQueue().put(sslsock);
correct = true;
} catch (UnknownHostException e) {
System.out.println("Please enter a valid IP Address or Hostname");
} catch (IOException e) {
System.out.println("Error connecting to host: Host might not be online");
}
}
}
} else if (obj instanceof SSLSocket) {
SSLSocket socket =(SSLSocket) obj;
ConsoleWriteThread toHost = new ConsoleWriteThread(System.in, socket.getOutputStream());
InetReadThread fromHost = new InetReadThread(socket.getInputStream(), System.out);
fromHost.start();
toHost.start();
System.out.println("Chat connection established");
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Connection terminated");
System.out.println("Press <enter> to exit");
try {
console.readLine();
} catch (IOException ex) {
}
System.exit(0);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -