/**
* 服务端以DataInputStream等待字节全部写入,阻塞时间受 SoTimeout (Socket operation Timeout)
*/
public class SocketServer {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(3216);
Socket socket = server.accept();
System.out.println("Socket communication build");
DataInputStream ois = new DataInputStream(socket.getInputStream());
int len1 = ois.readInt();
int len2 = ois.readInt();
System.out.println("len1 + len2="+ (len1 + len2));
socket.setSoTimeout(1000);//timeout设定影响socket的阻塞
byte[] data = new byte[len1+len2];
//plan1 全读等待
ois.readFully(data);
//plan2 直接read,读不全
// ois.read(data);
String str1 = new String(data, 0, len1);
String str2 = new String(data, len1, len2);
System.out.println(str1);
System.out.println(str2);
System.out.println(Arrays.toString(data));
server.close();
}
}
public class SocketClient {
public static void main(String[] args) throws Exception, IOException {
Socket socket = new Socket("127.0.0.1", 3216);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
byte[] str1 = "写信告诉我,今夜的海什么颜色".getBytes();
byte[] str2 = "夜夜陪着你的海,心情又如何".getBytes();
dos.writeInt(str1.length);
dos.writeInt(str2.length);
dos.write(str1);
TimeUnit.SECONDS.sleep(10);
dos.write(str2);
dos.flush();
dos.close();
socket.close();
}
}