当前位置:首页 > 开发 > 编程语言 > 网络编程 > 正文

java socket 长连接

发表于: 2014-03-01   作者:coach   来源:转载   浏览:
摘要: 长连接主要用于在少数客户端与服务端的频繁通信,因为这时候如果用短连接频繁通信常会发生Socket出错,并且频繁创建Socket连接也是对资源的浪费 简单说,如果是频繁通讯,使用长连接 长:connect连上后不断开,进行N次收发操作。 短:每次都connect,完成任务后立即断开。下次重连。 一般都是accept后启动一个线程去处理,该线程中的处理大致如下   &
长连接主要用于在少数客户端与服务端的频繁通信,因为这时候如果用短连接频繁通信常会发生Socket出错,并且频繁创建Socket连接也是对资源的浪费
简单说,如果是频繁通讯,使用长连接

长:connect连上后不断开,进行N次收发操作。
短:每次都connect,完成任务后立即断开。下次重连。
一般都是accept后启动一个线程去处理,该线程中的处理大致如下  
 
短连接: 
  run(){ 
      read           //读取请求包 
      process     //处理 
      write         //应答处理结果 
  }  
   
长连接: 
  run(){ 
    while(NotEnd){ 
        read 
        process 
        write 
      } 
  }



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;

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;

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();
						}
					}
				}
			}

		}
	}
}

java socket 长连接

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号