可中断套接字

当连接到一个套接字时,当前线程将会被阻塞直到建立连接或产生超时为止。通过套接字读写数据时也是一样。

在交互式的应用中,也许会考虑为用户提供一个功能,用已取消那些看似不会成功的连接,但是,当线程因套接字长时间无法响应而发生阻塞时,无法通过调用interrupt来解除阻塞。

如此,可用java.nio包提供的一个新特性——SocketChannel类中断套接字操作

1
SocketChannel channel=SocketChannel.open(new InetSocketAddress(host,port));

channel并没有与之相关联的流,实际上,它所拥有的read和write方法都是通过调用Buffer对象来实现的。ReadableByteChannel接口和WritableByteChannel都声明了这两个方法。如果不想处理缓存,可以使用Scanner类来读取信息,因为Scanner有一个带ReadableByteChannel参数的构造器:

1
2
3
Scanner in = new Scanner(channel);
OutputStream outStream=Channels.newOutputStream(channel);
//从通道获得输出流

如果线程发生中断,那么这些操作将不会陷入阻塞,而是以抛出异常的方式结束

示例程序如下

其对比了可中断套接字与阻塞套接字:服务器将连续发送数字,每发送一个数字停一下。点击两个按钮中的任何一个都会启动一个线程来连接服务器并打印输出。第一个使用可中断套接字,第二个使用阻塞套接字,启动之后,再点击取消时,可中断套接字一直工作良好,阻塞套接字却只能有效工作有限次,原因不明

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import javax.swing.*;
public class InterruptibleSocketTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new InterruptibleSocketFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

class InterruptibleSocketFrame extends JFrame
{
public InterruptibleSocketFrame()
{
setSize(WIDTH, HEIGHT);
setTitle("InterruptibleSocketTest");

JPanel northPanel = new JPanel();
add(northPanel, BorderLayout.NORTH);

messages = new JTextArea();
add(new JScrollPane(messages));

interruptibleButton = new JButton("Interruptible");
blockingButton = new JButton("Blocking");

northPanel.add(interruptibleButton);
northPanel.add(blockingButton);

interruptibleButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
interruptibleButton.setEnabled(false);
blockingButton.setEnabled(false);
cancelButton.setEnabled(true);
connectThread = new Thread(new Runnable()
{
public void run()
{
try
{
connectInterruptibly();
}
catch (IOException e)
{
messages.append("\nInterruptibleSocketTest.connectInterruptibly: " + e);
}
}
});
connectThread.start();
}
});

blockingButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
interruptibleButton.setEnabled(false);
blockingButton.setEnabled(false);
cancelButton.setEnabled(true);
connectThread = new Thread(new Runnable()
{
public void run()
{
try
{
connectBlocking();
}
catch (IOException e)
{
messages.append("\nInterruptibleSocketTest.connectBlocking: " + e);
}
}
});
connectThread.start();
}
});

cancelButton = new JButton("Cancel");
cancelButton.setEnabled(false);
northPanel.add(cancelButton);
cancelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
connectThread.interrupt();
cancelButton.setEnabled(false);
}
});
server = new TestServer();
new Thread(server).start();
}
public void connectInterruptibly() throws IOException
{
messages.append("Interruptible:\n");
SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost", 8189));
try
{
in = new Scanner(channel);
while (!Thread.currentThread().isInterrupted())
{
messages.append("Reading ");
if (in.hasNextLine())
{
String line = in.nextLine();
messages.append(line);
messages.append("\n");
}
}
}
finally
{
channel.close();
EventQueue.invokeLater(new Runnable()
{
public void run()
{
messages.append("Channel closed\n");
interruptibleButton.setEnabled(true);
blockingButton.setEnabled(true);
}
});
}
}
public void connectBlocking() throws IOException
{
messages.append("Blocking:\n");
Socket sock = new Socket("localhost", 8189);
try
{
in = new Scanner(sock.getInputStream());
while (!Thread.currentThread().isInterrupted())
{
messages.append("Reading ");
if (in.hasNextLine())
{
String line = in.nextLine();
messages.append(line);
messages.append("\n");
}
}
}
finally
{
sock.close();
EventQueue.invokeLater(new Runnable()
{
public void run()
{
messages.append("Socket closed\n");
interruptibleButton.setEnabled(true);
blockingButton.setEnabled(true);
}
});
}
}
class TestServer implements Runnable
{
public void run()
{
try
{
ServerSocket s = new ServerSocket(8189);

while (true)
{
Socket incoming = s.accept();
Runnable r = new TestServerHandler(incoming);
Thread t = new Thread(r);
t.start();
}
}
catch (IOException e)
{
messages.append("\nTestServer.run: " + e);
}
}
}
class TestServerHandler implements Runnable
{
/**
* Constructs a handler.
* @param i the incoming socket
*/
public TestServerHandler(Socket i)
{
incoming = i;
}

public void run()
{
try
{
OutputStream outStream = incoming.getOutputStream();
PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);
while (counter < 100)
{
counter++;
if (counter <= 10) out.println(counter);
Thread.sleep(100);
}
incoming.close();
messages.append("Closing server\n");
}
catch (Exception e)
{
messages.append("\nTestServerHandler.run: " + e);
}
}

private Socket incoming;
private int counter;
}

private Scanner in;
private JButton interruptibleButton;
private JButton blockingButton;
private JButton cancelButton;
private JTextArea messages;
private TestServer server;
private Thread connectThread;

public static final int WIDTH = 300;
public static final int HEIGHT = 300;
}

未解决问题:阻塞套接字未能正常工作,可能与其底层实现机制有关

Donate comment here