public class SocketTest extends Thread {
private Socket so;
private DataInputStream in;
public static void main(String[] args) {
SocketTest app = new SocketTest();
app.startup();
}
public void startup() {
try {
// 创建服务端socket对象并指定监听端口
ServerSocket ss = new ServerSocket(9999);
System.out.println("listening...");
// 等待客户端连接
so = ss.accept();
System.out.println("connected");
// 开始读取数据
start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
// 创建socket输入流
in = new DataInputStream(so.getInputStream());
while (true) {
try {
// 定义接收缓冲区(64字节)
byte[] buf = new byte[64];
// 将数据读到接收缓冲区中,并返回实际读到的数据长度
int len = in.read(buf, 0, 64);
// 长度为-1说明到达输入流末尾,socket已关闭
if (len < 1) {
System.out.println("closed");
break;
}
System.out.println("(" + len + ")");
} catch (Exception e) {
// 读数据异常
e.printStackTrace();
}
}
} catch (Exception e) {
// 监听异常
e.printStackTrace();
}
}
}