关闭

java socket长连接服务端

标签: 长连接服务端socket消息客户端
842人阅读 评论(0) 收藏 举报
分类:
java socket长连接服务端的实现

网络编程都是最底层都是基于socket的,鉴于客户端需要一直发送消息,使用短连接就不适合了,因为建立socket连接后发送完数据又马上断开连接。而长连接通过客户端的心跳机制一直保持连接,不管当前是否接收和发送数据。长连接服务端代码如下:

package com.starit.ipran.socket;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.starit.ipran.kafka.KafkaUtils;
import com.starit.ipran.load.Constants;
import com.starit.ipran.model.IpranAlarm;
import com.starit.ipran.util.EncodeUtils;


public class SocketServer {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(SocketServer.class);
	   
    public void startAction(){  
        ServerSocket serverSocket=null;  
        try {  
            serverSocket=new ServerSocket(Constants.SOCKET_PORT);  //端口号
            LOGGER.info("服务端服务启动监听:");
            //通过死循环开启长连接,开启线程去处理消息
            while(true){  
                Socket socket=serverSocket.accept();  
                new Thread(new MyRuns(socket)).start();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (serverSocket!=null) {  
                    serverSocket.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        }  
    }  
      
    class MyRuns implements Runnable{
          
        Socket socket;  
        BufferedReader reader;  
        BufferedWriter writer;  
  
        public MyRuns(Socket socket) {  
            super();  
            this.socket = socket;  
        }  
  
        public void run() {  
            try {  
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//读取客户端消息  
                writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));//向客户端写消息
                String lineString="";  
               
                while(!(lineString=reader.readLine()).equals("bye")){
                	LOGGER.info("收到来自客户端的发送的消息是:" + lineString);
                    writer.write("服务器返回:"+lineString+"\n");  
                    writer.flush();  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            } finally {  
                try {  
                    if (reader!=null) {  
                        reader.close();  
                    }  
                    if (writer!=null) {  
                        writer.close();  
                    }  
                    if (socket!=null) {  
                        socket.close();  
                    }  
                } catch (Exception e2) {  
                    e2.printStackTrace();  
                }  
            }  
        }  
          
    }  
}


下面是客户端程序:
package www.socket.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class Client {
	public static void main(String[] args) {  
		Client client=new Client();  
		client.startAction();  
    }  
      
    void readSocketInfo(BufferedReader reader){  
        new Thread(new MyRuns(reader)).start();  
    }  
      
    class MyRuns implements Runnable{  
          
        BufferedReader reader;  
          
        public MyRuns(BufferedReader reader) {  
            super();  
            this.reader = reader;  
        }  
  
        public void run() {  
            try {  
                String lineString="";  
                while( (lineString = reader.readLine())!=null ){  
                    System.out.println(lineString);  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
          
    }  
      
    public void startAction(){  
        Socket socket=null;  
        BufferedReader reader=null;  
        BufferedWriter writer=null;  
        BufferedReader reader2=null;  
        try {  
            socket=new Socket("127.0.0.1", 10000);  
            reader = new BufferedReader(new InputStreamReader(System.in));  
            reader2=new BufferedReader(new InputStreamReader(socket.getInputStream()));  
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));  
            readSocketInfo(reader2);  
            String lineString="";  
            while(!(lineString=reader.readLine()).equals("exit")){  
                writer.write(lineString+"\n");  
                writer.flush();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (reader!=null) {  
                    reader.close();  
                }  
                if (writer!=null) {  
                    writer.close();  
                }  
                if (socket!=null) {  
                    socket.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        }  
    }  
}




1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:28970次
    • 积分:831
    • 等级:
    • 排名:千里之外
    • 原创:52篇
    • 转载:0篇
    • 译文:0篇
    • 评论:10条
    贵州中测信息技术有限公司
    友情链接
    最新评论