nwclient.java
来自「面向对象的设计思想」· Java 代码 · 共 88 行
JAVA
88 行
import java.io.*;
import java.net.*;
class NwClient {
String host;
int port;
Socket skt;
InputStream is;
ObjectInputStream ois;
OutputStream os;
ObjectOutputStream oos;
int retry;
public NwClient(String host, int port) {
this.host = host;
this.port = port;
connect();
}
public void send(Object obj) throws Exception {
retry = 10;
while(retry > 0) {
try {
oos.writeObject(obj);
retry = 0;
} catch(Exception e) {
System.out.println("NwClient.send: " + e);
retry--;
if (retry == 0) {
throw e;
}
Thread.sleep(6000);
connect();
}
}
}
public Object receive() throws Exception{
Object obj = null;
try {
if (ois == null) {
ois = new ObjectInputStream(is);
}
obj = ois.readObject();
} catch(Exception e) {
System.out.println("NwClient.receive: " + e);
connect();
throw e;
}
return obj;
}
public void connect() {
try {
skt = new Socket(host, port);
is = skt.getInputStream();
ois = null;
os = skt.getOutputStream();
oos = new ObjectOutputStream(os);
} catch(Exception e) {
}
}
public void connect(String host, int port) {
this.host = host;
this.port = port;
connect();
}
public void close() {
try {
} finally {
if (skt != null) {
try {
skt.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?