创建阻塞的 EchoClient
客户程序一般不需要同时建立与服务器的多个连接,因此用一个线程,按照阻塞模式运行就能满足需求- public class EchoClient {
-
- private SocketChannel socketChannel = null;
-
- public EchoClient() throws IOException {
- socketChannel = SocketChannel.open();
- InetAddress ia = InetAddress,getLocalHost();
- InetSocketAddress isa = new InetSocketAddress(ia,8000);
- socketChannel.connect(isa); //连接服务器
- }
-
- 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(socketChannel.socket());
- PrintWriter pw = getWriter(socketChannel.socket());
-
- BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
-
- String msq = null;
-
- while((msg = localReader.readLine()) != null) {
- pw.println(msg);
- System.out.println(br.readLine());
- if(msq.equals("bye")) {
- break;
- }
- }
- } catch(IOException e) {
- e.printStackTrace();
- } finally {
- try {
- socketChannel.close();
- } catch(IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
复制代码 创建非阻塞的 EchoClient
对于客户与服务器之间的通信,按照它们收发数据的协调程度来区分,可分为同步通信和异步通信
同步通信指甲方向乙方发送了一批数据后,必须等接收到了乙方的响应数据后,再发送下一批数据。同步通信要求一个 IO 操作完成之后,才能完成下一个 IO 操作,用阻塞模式更容易实现
异步通信指发送数据和接收数据的操作互不干扰,各自独立进行。异步通信允许发送数据和接收数据的操作各自独立进行,用非阻塞模式更容易实现
值得注意的是,通信的两端并不要求都采用同样的通信方式,当一方采用同步通信时,另一方可以采用异步通信
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |