Repository navigation
Expand file tree
/
Copy pathLongConnTest.java
More file actions
67 lines (60 loc) · 2.16 KB
/
Copy pathLongConnTest.java
File metadata and controls
67 lines (60 loc) · 2.16 KB
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
package com.dz.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Scanner;
/**
* Created by RoyDeng on 18/2/3.
*/
public class LongConnTest {
private Logger logger = LoggerFactory.getLogger(LongConnTest.class);
String host = "localhost";
int port = 8080;
public void testLongConn() throws Exception {
logger.debug("start");
final Socket socket = new Socket();
socket.connect(new InetSocketAddress(host, port));
Scanner scanner = new Scanner(System.in);
new Thread(() -> {
while (true) {
try {
byte[] input = new byte[64];
int readByte = socket.getInputStream().read(input);
logger.debug("readByte " + readByte);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
int code;
while (true) {
code = scanner.nextInt();
logger.debug("input code:" + code);
if (code == 0) {
break;
} else if (code == 1) {
ByteBuffer byteBuffer = ByteBuffer.allocate(5);
byteBuffer.put((byte) 1);
byteBuffer.putInt(0);
socket.getOutputStream().write(byteBuffer.array());
logger.debug("write heart finish!");
} else if (code == 2) {
byte[] content = ("hello, I'm" + hashCode()).getBytes();
ByteBuffer byteBuffer = ByteBuffer.allocate(content.length + 5);
byteBuffer.put((byte) 2);
byteBuffer.putInt(content.length);
byteBuffer.put(content);
socket.getOutputStream().write(byteBuffer.array());
logger.debug("write content finish!");
}
}
socket.close();
}
// 因为Junit不支持用户输入,所以用main的方式来执行用例
public static void main(String[] args) throws Exception {
new LongConnTest().testLongConn();
}
}