LZ一直没有涉猎过长连接,原因不过多解释,懒可能是其中一个理由。突然有一天觉着是个遗憾,于是自己顺手用Socket搞了一个,包括长连接必须有的心跳机制,和对象的传递,当然用到了JAVA序列化,传递的对象必须实现java.io.Serializable接口。
客户端:
package com.feng.test.longconnection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.ArrayList; /** * * @author songfeng * @version 1.0 * @since 2015-10-14 * @category com.feng.test.longconnection * */ public class Client { private Socket socket; private String ip; private int port; private String id; ObjectOutputStream oos; BufferedReader br; public Client(String ip, int port,String id) { try { this.ip = ip; this.port = port; this.id = id; this.socket = new Socket(ip, port); this.socket.setKeepAlive(true); oos = new ObjectOutputStream(socket.getOutputStream()); br = new BufferedReader(new InputStreamReader(socket.getInputStream())); new Thread(new heartThread()).start(); new Thread(new MsgThread()).start(); } catch (Exception e) { e.printStackTrace(); } } public void sendMsg(Object content) { try { oos.writeObject(content); oos.flush(); } catch (Exception e) { closeSocket(); } } public void closeSocket() { try { socket.close(); oos.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } class heartThread implements Runnable { @Override public void run() { while(true) { try { Thread.sleep(1000); long time = System.currentTimeMillis(); //System.out.println("client send:" + time); sendMsg("Client" + id + " send:" + time); } catch (InterruptedException e) { e.printStackTrace(); } } } } class MsgThread implements Runnable { @Override public void run() { String str = null; while(true) { try { if(socket.getInputStream().available() > 0) { while((str = br.readLine()) != null) { System.out.println(str); } } } catch (IOException e) { closeSocket(); } } } } public static void main(String[] args) { Client client1 = new Client("127.0.0.1", 55555, "1"); client1.sendMsg(new Pojo("songfeng", 26, new ArrayList<String>())); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } Client client2 = new Client("127.0.0.1", 55555, "2"); } }
服务端:
package com.feng.test.longconnection; import java.io.BufferedWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * * @author songfeng * @version 1.0 * @since 2015-10-14 * @category com.feng.test.longconnection * */ public class Server { private ServerSocket serverSocket; private Socket socket; private int port; static List<Socket> list = new ArrayList<Socket>(); ExecutorService exec; public Server(int port) { try { this.port = port; this.serverSocket = new ServerSocket(port); //线程池管理客户端线程。 exec = Executors.newCachedThreadPool(); while (true) { socket = serverSocket.accept(); list.add(socket); exec.execute(new MsgThread(socket)); } } catch (IOException e) { e.printStackTrace(); } } public void closeSocket() { try { for(Socket s : list) { s.close(); } serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } class MsgThread implements Runnable { private Socket socket; private long lastHeatTime = System.currentTimeMillis(); public MsgThread(Socket socket) { this.socket = socket; } @Override public void run() { ObjectInputStream oin = null; PrintWriter pw = null; String str = null; try { oin = new ObjectInputStream(this.socket.getInputStream()); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()))); while(true) { if(!socket.isConnected()) { break; } if(socket.getInputStream().available() > 0) { if(System.currentTimeMillis() - lastHeatTime > 5000) { break; } oin.readFields(); Object object = oin.readObject(); if(object instanceof String) { lastHeatTime = System.currentTimeMillis(); long time = System.currentTimeMillis(); pw.println(object + ",Server back:" + time); pw.flush(); } else if(object instanceof Pojo) { pw.println(object + ",Server back:" + ((Pojo)object).getName()); pw.flush(); } } } } catch (Exception e) { e.printStackTrace(); } finally { try { this.socket.close(); list.remove(socket); if(oin != null) { oin.close(); } pw.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { Server server = new Server(55555); } }
数据类:
package com.feng.test.longconnection; import java.io.Serializable; import java.util.List; /** * * @author songfeng * @version 1.0 * @since 2015-10-16 * @category com.feng.test.longconnection * */ public class Pojo implements Serializable { /** * 序列化 */ private static final long serialVersionUID = -8868529619983791261L; private String name; private int age; private List<String> likeThing; public Pojo(String name, int age, List<String> likeThing) { super(); this.name = name; this.age = age; this.likeThing = likeThing; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<String> getLikeThing() { return likeThing; } public void setLikeThing(List<String> likeThing) { this.likeThing = likeThing; } }
相关推荐
Socket长连接+心跳包+发送+读取,用到的全在这里了,自己看看哪里不需要的就不要添加了!代码很清晰很明白了!
这是Android的socket长连接(心跳包),由于本人项目中需要用到长连接,所以先做了个demo,亲测是没有问题的。
Socket长连接、通信、心跳包、消息回调、Java服务端
socket 长连接 简单例子,适合初学的朋友,里面有多线程 实现的,包括心跳包,数据分为两部分传送,首先双方约定用一个4字节的数组告诉对方要传送数据的长度,然后在写入数据,这样长连接的时候,双方可以知道对方...
本人测试可用,分析下安卓的Socket长连接心跳,实现了服务端和客户端
tcp长连接,与服务器端保持长连接,发送心跳包。保持连接。
主要是关于java tcp长连接,心跳连接源码。
Android Socket连接,包含心跳检测,断线重连,数据发送等等 博客地址:http://blog.csdn.net/yuzhiqiang_1993/article/details/78094909
C#高级编程之实现Socket心跳机制,TCP网络长连接。 心跳包之所以叫心跳包是因为:它像心跳一样每隔固定时间发一次,以此来告诉服务器,这个客户端还活着。事实上这是为了保持长连接,至于这个包的内容,是没有什么...
Android Socket连接,包含心跳检测,断线重连,数据发送等等 博客地址:http://blog.csdn.net/yuzhiqiang_1993/article/details/78094909
Android_socket通信加长连接(有心跳检测)都有注释,代码简洁
mina带心跳长链接,可实现服务间通信。socket长连接实现客户端与服务端的通信。对于通信技术学习是非常好的资料。改造后可实现企业应用
一个Socket连接管理器(心跳机制)
很多人在写Socket的时候会遇到心跳包响应机制跟主线程消息传输机制如何规避而互不影响,本Demo就解决了此问题,而且简单易懂,都有备注,欢迎下载学习之用。
客户端与服务端保持在线的心跳连接代码示例。一般用于保持socket长连接或者周期性上传客户端状态。
安卓端使用socket TCP/IP通讯实现安卓手机端和服务器的长连接,心跳包的发送,实现即时通讯。
iOS基于NSStream实现的Socket长连接小封装
定制心跳对象,客户端心跳机制发送数据,保证连接,服务器延时检查,超时的断开连接,支持多客户端连接,并相应心跳对象
winform的socket通信中连接是否正常,最好通过心跳包来确定,本程序就是一个简单的心跳包实例,简单、易懂~
Android的socket长连接(心跳检测),有服务端和客户端 。开发环境eclipse。