Java Socket长连接实现

TestScoket.java

单例模式实现,继承Socket

复制代码
 1 public class TestSocket
 2         extends Socket {
 3     
 4     private static TestSocket instance;
 5     
 6     private TestSocket() {
 7     }
 8     
 9     private TestSocket(String ip,int port) throws UnknownHostException, IOException{
10         super(ip,port);
11     }
12     
13     public static synchronized TestSocket getInstance(String ip,int port) throws UnknownHostException, IOException {
14         if (instance == null) {
15             instance = new TestSocket(ip,port);
16             instance.setKeepAlive(true);  //主要是这个参数来保持连接的
17             instance.setSoTimeout(60);
18         }
19         return instance;
20     }
21 }
复制代码

调用代码

复制代码
DdzSocket socket = DdzSocket.getInstance("127.0.0.1", "8000");
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write("发送字符串".getBytes("UTF-8"));
        
dos.write(baos.toByteArray());
dos.flush();
复制代码

服务端程序可自行在网上找一个这里就不贴出来了,

你可能感兴趣的:(java,java,socket,cc++)