socket系列(一)——socket实现推送
来源:互联网 发布:ubuntu分区工具 编辑:程序博客网 时间:2024/06/03 05:16
Javasocket实现推送
实现
设想:用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()话,它只会在连接结束后才把缓存的数据读取出来。
阅读全文
0 0
- socket系列(一)——socket实现推送
- Socket层实现系列 — bind()的实现(一)
- Socket层实现系列 — accept()的实现(一)
- socket系列(三)——Spring-socket实时通信、推送
- Android socket 编程 实现消息推送(一)
- Android socket 编程 实现消息推送(一)
- java socket编程(1)——利用socket实现聊天之消息推送
- Android深入浅出系列之Socket—Socket编程(一)
- Android深入浅出系列之Socket—Socket编程(一)
- Android深入浅出系列之Socket—Socket编程(一)
- Socket实现消息推送
- Socket层实现系列 — bind()的实现(二)
- Socket层实现系列 — accept()的实现(二)
- socket系列(二)——Javaee实现实时通信
- 【Java Socket】入门系列 3.1.通过 Socket 实现 TCP 编程 — Socket简介
- Java Socket 实现语音推送
- socket系列之客户端socket——Socket类
- socket推送
- 七、多线程(未完.待更)
- Android17
- Angular的一些坑
- C++实验6——字符串操作
- 网络编程之开源项目和JSON解析技术的使用——简易新闻客户端
- socket系列(一)——socket实现推送
- android18
- css之元素的显示方式
- tensorflow实现对图片的读取
- 正则语言引擎:一个简单LEX和YACC结合运用的实例
- spark 2.1 TaskResult
- postfix
- android18
- 用c语言链表实现通讯录