版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/luo4105/article/details/72689843
设想:用socket实现服务器与客户端的tcp长连接,保持outputStream、InputStream连接,通过输入输出流实现信息实时推送
代码
public classTestPush {
@SuppressWarnings("resource")
@Test
public void pushService() throws IOException {
ServerSocketserviceSocket= newServerSocket(10888);
while(true) {
Socketsocket= serviceSocket.accept();
InputStreamclientMsgIs= socket.getInputStream();
StringclientMsg= StreamUtil.inputStreamToString(clientMsgIs, "UTF-8");
System.out.println(clientMsg);
socket.shutdownInput();
System.out.println("请输入推送信息:");
Scannersc = new Scanner(System.in);
StringpushMsg= sc.nextLine();
OutputStreamserviceOs= socket.getOutputStream();
BufferedWriterwriter= newBufferedWriter(newOutputStreamWriter(serviceOs));
while(!"end".equals(pushMsg)) {
writer.write(pushMsg);
writer.newLine();
writer.flush();
System.out.println("请输入推送信息:");
sc = new Scanner(System.in);
pushMsg = sc.nextLine();
}
socket.shutdownOutput();
serviceOs.close();
socket.close();
}
}
@SuppressWarnings("resource")
@Test
public void pushClient() throws UnknownHostException,IOException {
Socketsocket= newSocket("127.0.0.1", 10888);
OutputStreamos = socket.getOutputStream();
Stringcmsg= "client connect success";
os.write(cmsg.getBytes("UTF-8"));
os.flush(); //这是socket强制发送
socket.shutdownOutput();
InputStreamserviceMsgIs= socket.getInputStream();
BufferedReaderreader= newBufferedReader(newInputStreamReader(serviceMsgIs));
Stringcontent= null;
while(true) {
if((content = reader.readLine()) != null) {
System.out.println(content);
}
}
}
}
用junit将两个方法运行一下,效果如下
这只是一个了解原理的demo,有很都多不完善的地方。
注意的是这里只能使用readline()和write.newLine()的原因是客户端InputStream接收到含有换行符的时候,就会把inputStream缓存的数据拿出来,而如果直接使用InputStream.read()话,它只会在连接结束后才把缓存的数据读取出来。