网络编程-TCP连接-length
在使用readLine方式时,常常会遇到因为没有结束标记,而导致阻塞现象。
如果不想使用结束标记,这里可以使用一个固定长度的byte[],来获取流。
server
package com.net.tcp.length; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class MyServerL { public static void main(String[] args) { ServerSocket ss; try { ss = new ServerSocket(30000); Socket s= ss.accept(); byte[] rin = new byte[8]; s.getInputStream().read(rin); System.out.println(new String(rin,0,8)); PrintStream ps = new PrintStream(s.getOutputStream()); ps.println("收到消息aa"); ps.flush(); ps.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Client
package com.net.tcp.length; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.InetSocketAddress; import java.net.Socket; public class MyClientL { public static void main(String[] args) { Socket s = new Socket(); try { s.connect(new InetSocketAddress("127.0.0.1", 30000), 10000); PrintStream ps = new PrintStream(s.getOutputStream()); ps.println("发送消息aa"); ps.flush(); byte[] rin = new byte[8]; s.getInputStream().read(rin); System.out.println(new String(rin,0,8)); ps.close(); s.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
本文来自博客园,作者:月色深潭,交流群:733423266,转载请注明原文链接:https://www.cnblogs.com/moonpool/p/5518866.html