关于java socket中的read方法阻塞问题

    前几天一个有个同学咨询我关于java socket编程的一些问题,因为我这个同学今年刚从.NET转到java 对于java的IO体系不是很清楚,在给他解答一些问题时我自己也总结了比较容易出错的问题。

  我们直接贴一段socket代码看一下

客户端: public class SocketClient { public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException { Socket client = new Socket("localhost",8888); OutputStream out = client.getOutputStream(); InputStream input = client.getInputStream(); out.write("sender say hello socket".getBytes()); out.flush(); read(input); out.close(); } public static void read(InputStream input) throws IOException { byte[] buf = new byte[128]; int size = 0; while ((size = input.read(buf,0,buf.length)) != -1) { System.out.print(new String(buf)); } } } 服务端: public class SocketServer { public static void main(String[] args) { SocketServer ss = new SocketServer(); int port = 8888; try { ss.startServer(port); } catch (Exception e) { e.printStackTrace(); } } public void startServer(int port) throws Exception { ServerSocket serverSocket = new ServerSocket(port); Socket server = null; try { while (true) { server = serverSocket.accept(); System.out.println("server socket is start……"); try { BufferedReader input = new BufferedReader(new InputStreamReader(new ByteArrayInputStream("服务端发给客户端的信息".getBytes()))); BufferedInputStream in = new BufferedInputStream(server.getInputStream()); PrintWriter out = newPrintWriter(newOutputStreamWriter(server.getOutputStream())); String clientstring = null; out.println("欢迎客户端连入"); out.flush(); byte[] buf = new byte[128]; int size = 0; while (( size = in.read(buf,0,buf.length)) != -1) { System.out.println(new String(buf)); } out.print(" client is over"); out.flush(); out.close(); System.out.println(" client is over"); } catch (Exception e) { e.printStackTrace(); } finally { server.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { serverSocket.close(); } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsxsfs.html