`
jiewo
  • 浏览: 47382 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

java socket 长连接

    博客分类:
  • java
阅读更多
最近做SSO的项目,其中用到了socket长连接.一直都是看代码的,但是要求socket做成SSL的,不得不动手写写代码了.下面我给出一个简单的socket长连接.
SocketClient.java
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.CharBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/*{  user:jiangwh }*/

public class SocketClient {

	public static final Object locked = new Object();
	public static final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(
			1024 * 100);

	class SendThread extends Thread{
		private Socket socket;
		public SendThread(Socket socket) {
			this.socket = socket;
		}
		@Override
		public void run() {
			while(true){
				try {
					String send = getSend();			
					PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
					pw.write(send);
					pw.flush();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		public String getSend() throws InterruptedException{
			Thread.sleep(1000);
			return "<SOAP-ENV:Envelope>"+System.currentTimeMillis()+"</SOAP-ENV:Envelope>";
		}
	}

	class ReceiveThread extends Thread{
		private Socket socket;
		
		public ReceiveThread(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			while(true){
				try {					
					Reader reader = new InputStreamReader(socket.getInputStream());
					CharBuffer charBuffer = CharBuffer.allocate(8192);
					int index = -1;
					while((index=reader.read(charBuffer))!=-1){
						charBuffer.flip();
						System.out.println("client:"+charBuffer.toString());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void start() throws UnknownHostException, IOException{
		Socket socket = new Socket("10.10.148.40",18889);
		new SendThread(socket).start();
		new ReceiveThread(socket).start();
	}
	public static void main(String[] args) throws UnknownHostException, IOException {
		new SocketClient().start();
	}
}
SocketServer.java
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.CharBuffer;
import java.util.Date;

/*{user:jiangwh }*/

public class SocketServer {

	private final static String SOAP_BEGIN = "<SOAP-ENV:Envelope";
	private final static String SOAP_END = "</SOAP-ENV:Envelope>";

	public static void main(String[] args) throws IOException {
		SocketServer socketServer = new SocketServer();
		socketServer.start();
	}

	public void start() throws IOException {
		ServerSocket serverSocket = new ServerSocket(18889);
		while (true) {
			Socket socket = serverSocket.accept();
			new SocketThread(socket).start();
		}
	}

	class SocketThread extends Thread {
		private Socket socket;
		private String temp;

		public Socket getSocket() {
			return socket;
		}

		public void setSocket(Socket socket) {
			this.socket = socket;
		}

		public SocketThread(Socket socket) {
			this.socket = socket;
		}

		public void run() {
			try {
				Reader reader = new InputStreamReader(socket.getInputStream());
				Writer writer = new PrintWriter(new OutputStreamWriter(socket
						.getOutputStream(), "GBK"));
				CharBuffer charBuffer = CharBuffer.allocate(8192);
				int readIndex = -1;
				while ((readIndex = reader.read(charBuffer)) != -1) {
					charBuffer.flip();
					temp += charBuffer.toString();
					if (temp.indexOf(SOAP_BEGIN) != -1
							&& temp.indexOf(SOAP_END) != -1) {
						// 传送一个soap报文
						System.out.println(new Date().toLocaleString()+"server:"+temp);
						temp="";
						writer.write("receive the soap message");
						writer.flush();
					} else if (temp.indexOf(SOAP_BEGIN) != -1) {
						// 包含开始,但不包含
						temp = temp.substring(temp.indexOf(SOAP_BEGIN));
					}	
					if (temp.length() > 1024 * 16) {
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (socket != null) {
					if (!socket.isClosed()) {
						try {
							socket.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}

		}
	}
}
分享到:
评论
8 楼 jiewo 2015-04-18  
Thomsonxu 写道
jiewo 写道
廖世勇 写道
finally { 
                if (socket != null) { 
                    if (!socket.isClosed()) { 
                        try { 
                            socket.close(); 
                        } catch (IOException e) { 
                            e.printStackTrace(); 
                        } 
                    } 
                } 
            } 

都把客户端socket给关闭了,是长连接吗?

socket异常才会走到finaly,正常情况不会关闭!!!!

finally是必须要执行的啊,无论异常与否!


finally的用法是这样的,但是上面的循环不会结束。你可以做下代码测试,看看server端接收了多少个连接。
7 楼 submaze 2015-04-07  
这个不是长连接啊
6 楼 myumen 2014-11-25  
这个真不叫长连接。示例只是读取了一条完整的SOAP消息而已(分多次read),而且读取完就关闭掉了SOCKET(While循环结束)。长连接应该是这样的:有消息就接收消息,没消息就定时发送心跳包并接收服务器返回以此来判断连接是否还在,Socket或者SocketChannel一般不会关闭。通常会有个异步线程定时发送心跳包。
5 楼 cuiyong_xu 2014-11-24  
这都看不懂,还做什么开发?
4 楼 Thomsonxu 2014-11-04  
jiewo 写道
廖世勇 写道
finally { 
                if (socket != null) { 
                    if (!socket.isClosed()) { 
                        try { 
                            socket.close(); 
                        } catch (IOException e) { 
                            e.printStackTrace(); 
                        } 
                    } 
                } 
            } 

都把客户端socket给关闭了,是长连接吗?

socket异常才会走到finaly,正常情况不会关闭!!!!

finally是必须要执行的啊,无论异常与否!
3 楼 wupy 2014-10-14  
finnal是必须走的把,无论怎么样都走的
2 楼 jiewo 2014-06-05  
廖世勇 写道
finally { 
                if (socket != null) { 
                    if (!socket.isClosed()) { 
                        try { 
                            socket.close(); 
                        } catch (IOException e) { 
                            e.printStackTrace(); 
                        } 
                    } 
                } 
            } 

都把客户端socket给关闭了,是长连接吗?

socket异常才会走到finaly,正常情况不会关闭!!!!
1 楼 廖世勇 2014-05-27  
finally { 
                if (socket != null) { 
                    if (!socket.isClosed()) { 
                        try { 
                            socket.close(); 
                        } catch (IOException e) { 
                            e.printStackTrace(); 
                        } 
                    } 
                } 
            } 

都把客户端socket给关闭了,是长连接吗?

相关推荐

Global site tag (gtag.js) - Google Analytics