()方法。
InputStream socketIn = socket.getInputStream();
OutputStream socketOut = socket.getOutputStream();
源代码EchoClient.java
public class EchoClient {
private String host = "localhost";
private int port = 8000;
private Socket socket;
public EchoClient() throws IOException {
socket = new Socket(host, port);
}
public static void main(String args[]) throws IOException {
new EchoClient().talk();
}
private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream socketOut = socket.getOutputStream();
return new PrintWriter(socketOut, true);
}
private BufferedReader getReader(Socket socket) throws IOException {
InputStream socketIn = socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public void talk() throws IOException {
try {
BufferedReader br = getReader(socket);
PrintWriter pw = getWriter(socket);
BufferedReader localReader = new BufferedReader(
new InputStreamReader(System.in));
String msg = null;
while ((msg = localReader.readLine()) != null) {
pw.println(msg);
System.out.println(br.readLine());
if (msg.equals("bye"))
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java Socket构建阻塞的TCP通信(3)
时间:2011-07-22 “子 孑” 博客
3.关闭Socket
1.关闭Socket的代码;
try {
……
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Socket类提供3个状态测试方法。
-isClosed():如果Socket已经连接到远程主机,并且还没有关闭,则返回true;
-isConnected():如果Socket曾经连接到远程主机,则返回true;
-isBound():如果Socket已经与一个本地端口绑定,则返回true。
判断一个Socket对象当前是否处于连接状态,
Boolean isConnected = socket.isConnected() && !socket.isClosed();
2.处理关闭
(1)当进程A与进程B交换的是字符流,并且是一行一行地读写数据时,可以事先约定一个特殊的标志 。
BufferedReader br = getReader(socket);
PrintWriter pw = getWriter(socket);
String msg = null;
while ((msg = br.readLine()) != null) {
System.out.println(msg);
pw.println(echo(msg));
if (msg.equals("bye")) // 如果客户发送的消息为“bye”,就结束通信
break;
}
(2)进程A先发送一个消息,告诉进程B所发送的正文长度,然后发送正文。进程B只要读取完该长度 的数据就可以停止读数据。
(3)进程A发送完所有数据后,关闭Socket。当进程B读入进程A发送的所有数据后,再次执行输入流 的read()方法时,该方法返回-1.
InputStream socketIn = socket.getInputStream();
ByteArrayOutputStream buffer = ne
|